【发布时间】:2021-05-18 12:23:40
【问题描述】:
我引用了这个答案:https://stackoverflow.com/a/57592970/8616895
当底部模式被WhenComplete关闭时尝试获取selectedValue。
WhenComplete() 中的函数被调用,但是当我打印 selectedValue 时,它只响应默认值 0。我已经检查过 SelectedValue 在我旋转时确实发生了变化,但是当我关闭时没有检索到正确的值modal,我认为它与异步或范围有关。请分享任何建议。
我的班级如下:
class PopupButton extends StatefulWidget {
final String initialValue;
final List<dynamic> options;
final Function callback;
int initialIndex;
PopupButton(
{@required this.initialValue,
@required this.options,
this.callback,
this.initialIndex = 0});
@override
_PopupButtonState createState() => _PopupButtonState();
}
class _PopupButtonState extends State<PopupButton> {
int selectedValue;
String text = "";
void showPicker(
BuildContext context,
) {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return Container(
height: 200,
child: CupertinoPicker(
itemExtent: 32,
onSelectedItemChanged: (value) {
if (mounted) {
setState(() {
selectedValue = value;
});
}
},
children: (widget.options.map((option) => Text(
option,
style: TextStyles.headerLight,
))).toList()),
);
}).whenComplete(() {
// THIS ALWAYS PRINTS 0
print("Selected: $selectedValue");
if (widget.callback != null) {
widget.callback(selectedValue);
}
TextEditingController();
return;
});
}
@override
Widget build(BuildContext context) {
selectedValue = widget.initialIndex;
text = widget.initialValue;
return GestureDetector(
child: Text(text),
onTap: () {
showPicker(context);
},
);
}
}
【问题讨论】: