我有简单的水平ListviewBuilder,里面有可以选择的卡。但是问题是,当我选择一张卡时,所有的卡都被选中了。我想要的是我只能选择1张卡,如果我选择另一张卡,删除旧的选择并创建新的选择到新卡。怎么做?
是这样的:

我失败的结果

这是我的源代码:
import 'package:flutter/material.dart';
class IconMenu {
final IconData iconName;
final String titleIcon;
IconMenu({this.iconName, this.titleIcon});
}
List<IconMenu> iconList = [
IconMenu(iconName: Icons.ac_unit, titleIcon: "AC Unit"),
IconMenu(iconName: Icons.access_alarm, titleIcon: "Alarm"),
IconMenu(iconName: Icons.accessibility_new, titleIcon: "accessiblity"),
IconMenu(iconName: Icons.add, titleIcon: "Add"),
];
class TestingScreen extends StatefulWidget {
static const routeName = "/testing-page";
@override
_TestingScreenState createState() => _TestingScreenState();
}
class _TestingScreenState extends State<TestingScreen> {
bool selectedList = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: iconList.length,
itemBuilder: (BuildContext context, int index) {
return InkWell(
onTap: () => setState(() => selectedList = !selectedList),
child: Container(
width: 150,
child: Card(
shape: selectedList
? RoundedRectangleBorder(
side: BorderSide(color: Colors.green))
: null,
elevation: 5,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Icon(iconList[index].iconName),
Text(iconList[index].titleIcon)
],
),
),
),
);
},
),
)
],
),
);
}
}发布于 2019-12-29 07:43:06
您应该为所选的索引取一个int。
int selectedIndex=-1
然后,您可以检查每一张卡,如果它的position等于selectedIndex,那么它就被选中了。
class _TestingScreenState extends State<TestingScreen> {
int selectedIndex = -1;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: iconList.length,
itemBuilder: (BuildContext context, int position) {
return InkWell(
onTap: () => setState(() => selectedIndex=position),
child: Container(
width: 150,
child: Card(
shape: (selectedIndex==position)
? RoundedRectangleBorder(
side: BorderSide(color: Colors.green))
: null,
elevation: 5,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Icon(iconList[position].iconName),
Text(iconList[position].titleIcon)
],
),
),
),
);
},
),
)
],
),
);
}
}https://stackoverflow.com/questions/59517592
复制相似问题