首页 > 解决方案 > AlertDialog 中的 Flutter NumberPicker 无法正常工作

问题描述

当我用 NumberPicker 选择一个新值时,它总是跳回到以前的值而不是当前选择的值。

我在 AlertDialog 中使用 NumberPicker,并使用 pickValue() 函数调用 NumberPicker。

  void pickValue() {
    showDialog<int>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("Wähle eine Aufgabenanzahl"),
            content: NumberPicker(
              selectedTextStyle: TextStyle(color: Colors.red),
              value: currentValue,
              minValue: 1,
              maxValue: 10,
              onChanged: (value) => setState(() => currentValue = value),
            ),
            actions: [
              TextButton(
                child: Text("OK", style: TextStyles.body),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        });
  }

标签: flutter

解决方案


将警报对话框的内容包装在StatefulBuilder. 它将提供一个新的上下文和一个 setState 函数来重建小部件。

void pickValue() {
showDialog<int>(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text("Wähle eine Aufgabenanzahl"),
        content:StatefulBuilder(
          builder: (context, setState) {
            return NumberPicker(
                selectedTextStyle: TextStyle(color: Colors.red),
                value: currentValue,
                minValue: 1,
                maxValue: 10,
                onChanged: (value) => setState(() => currentValue = value),
              );
          }
        ),
         
        actions: [
          TextButton(
            child: Text("OK", style: TextStyles.body),
            onPressed: () {
              Navigator.of(context).pop();
            },
          )
        ],
      );
    });
}

推荐阅读