Flutterでアプリ開発中,この問題に直面して調べていたのですが,
日本語で解決方法を載せている方が見当たらなかったため作成しました.
問題
showModalBottomSheet上に配置したChoiceChipを選択しても更新されない.
showModalBottomSheetを動かすとChoiceChipが更新されるため,変数の代入が問題ではない.
解決方法
ChoiceChipをStatefulBuilderで囲むと解決します.
Code
example.dart
...
Future<void> showBottomSheet(BuildContext context) {
int choiceIndex = 0;
return showModalBottomSheet<dynamic>(
context: context,
builder: (BuildContext context) {
return SizedBox(
height: 844,
child: Column(
children: [
+ StatefulBuilder(
+ builder: (BuildContext context, StateSetter setState) {
+ return
Container(
padding: const EdgeInsets.only(top: 20),
child: Wrap(
spacing: 20,
children: [
ChoiceChip(
label: const Text("選択 1"),
selected: choiceIndex == 0,
backgroundColor: Colors.grey[700],
selectedColor: Colors.white,
onSelected: (_) {
setState(() {
choiceIndex = 0;
});
},
),
ChoiceChip(
label: const Text("選択 2"),
selected: choiceIndex == 1,
backgroundColor: Colors.grey[700],
selectedColor: Colors.white,
onSelected: (_) {
setState(() {
choiceIndex = 1;
});
},
),
],
),
);
+ },
+ ),
SizedBox(
height: 300,
child: CupertinoDatePicker(
use24hFormat: true,
initialDateTime: DateTime.now(),
mode: CupertinoDatePickerMode.time,
onDateTimeChanged: (time) {},
)),
],
),
);
},
);
}
...