您不能分配定义哪个的责任CustomWidget
被选择为自己的CustomWidget
. A CustomWidget
一定不知道其他人的存在CustomWidget
s,也没有关于他们所持有的信息的任何信息。
鉴于此,您的CustomWidget
应该是这样的:
class CustomWidget extends StatefulWidget {
final int index;
final bool isSelected;
final VoidCallback onSelect;
const CustomWidget({
Key key,
@required this.index,
@required this.isSelected,
@required this.onSelect,
}) : assert(index != null),
assert(isSelected != null),
assert(onSelect != null),
super(key: key);
@override
_CustomWidgetState createState() => _CustomWidgetState();
}
class _CustomWidgetState extends State<CustomWidget> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onSelect,
child: Container(
margin: EdgeInsets.all(5.0),
child: ListTile(
title: Text("Title ${widget.index}"),
subtitle: Text("Description ${widget.index}"),
),
decoration: widget.isSelected
? BoxDecoration(color: Colors.black38, border: Border.all(color: Colors.black))
: BoxDecoration(),
),
);
}
}
以及使用的小部件CustomWidget
:
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int currentSelectedIndex;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Selected index is $currentSelectedIndex'),
),
body: ListView.builder(
itemCount: 3,
itemBuilder: (context, index) {
return CustomWidget(
index: index,
isSelected: currentSelectedIndex == index,
onSelect: () {
setState(() {
currentSelectedIndex = index;
});
},
);
},
),
);
}
}