here解决方案适用于单一ChoiceChip
需要多个ChoiceChip,但索引(选定)始终相同
下面是代码:它似乎需要另一个变量来存储所需的值,但不确定从哪里开始(也许使用提供程序?)
class _MyHomePageState extends State<MyHomePage> {
int _selectedIndex = 0;
Widget _buildChips(options) {
List<Widget> chips = [];
for (int i = 0; i < options.length; i++) {
ChoiceChip choiceChip = ChoiceChip(
selected: _selectedIndex == i,
label: Text(options[i], style: const TextStyle(color: Colors.white)),
elevation: 3,
pressElevation: 5,
backgroundColor: Colors.grey[400],
selectedColor: Colors.lightGreen,
onSelected: (bool selected) {
setState(() {
if (selected) {
_selectedIndex = i;
}
});
},
);
chips.add(choiceChip);
}
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: chips,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('Select A value'),
_buildChips(['Regular', 'Hard Sleeper', 'Soft Sleeper']),
const Text('Select B value'),
_buildChips(['Python', 'Flutter']),
ElevatedButton(
child: const Text('Pass selected A and B values to next screen'),
onPressed: () {print(_selectedIndex);},
),
],
),
),
);
}
}
1条答案
按热度按时间pu3pd22g1#
可以使用get包和GetXController
https://pub.dev/packages/get