【问题标题】:Flutter setting variable of CupertinoPicker after showModalBottomSheetshowModalBottomSheet 后 CupertinoPicker 的 Flutter 设置变量
【发布时间】: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);
      },
    );
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您的错误是在构建方法中初始化selectedValue。 每次打电话

    setState(() {
      selectedValue = value;
    });
    

    widget.initialIndex发起的selectedValue

    请将selectedValue = widget.initialIndex; 移至initState 方法。

    @override
    void initState() {
      super.initState();
      selectedValue = widget.initialIndex;
      text = widget.initialValue;
    }
    
    @override
      Widget build(BuildContext context) {
        return GestureDetector(
          child: Text(text),
          onTap: () {
            showPicker(context);
          },
        );
      }
    

    【讨论】:

      猜你喜欢
      • 2019-12-07
      • 2020-10-01
      • 1970-01-01
      • 2021-01-06
      • 2019-12-26
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多