尝试下面的代码希望对您有所帮助。 请参阅 ValueNotifier 和 ValueListenableBuilder 以更改状态。 根据您的需要更改容器的文本和颜色。
注意:您也可以使用 setState 来更改状态。
class ExampleApp extends StatelessWidget {
ExampleApp({Key? key}) : super(key: key);
ValueNotifier<int> selectedContainer = ValueNotifier<int>(-1);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SizedBox(
height: 100,
child: ListView.builder(
itemCount: 10,
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return ValueListenableBuilder(
valueListenable: selectedContainer,
builder: (context, selectedIndex, child) {
return GestureDetector(
onTap: () {
selectedContainer.value = index;
},
child: Column(
children: [
Container(
height: 60,
width: 60,
margin: EdgeInsets.symmetric(horizontal: 5),
decoration: BoxDecoration(
color: Colors.grey,
shape: BoxShape.circle,
border: Border.all(
color: selectedContainer.value == index
? Colors.red
: Colors.transparent)),
),
SizedBox(height: 15),
selectedContainer.value == index
? Text(
'Index - $index',
textAlign: TextAlign.center,
)
: SizedBox(),
],
),
);
},
);
},
),
),
),
);
}
}
结果屏幕: 选择项目之前
选择项目后