这是我的输出,但当我添加共享首选项时,会显示如下所述的错误.

enter image description here

我在项目中使用了共享首选项依赖关系.在最初打开的应用程序第一下拉值必须是'howmany'和第二下拉值'which',但当 Select 任何其他值并单击下一步按钮并从移动设备关闭应用程序时,用户重新打开时,则应显示用户 Select 的值.

例如:在初始用户打开的应用程序中,第一个下拉菜单的值必须是"多少",第二个"哪个",然后他 Select 第一个下拉菜单"three",第二个下拉菜单"4th",并在关闭应用程序并从最近的应用程序中删除后单击下一步按钮.稍后,当他重新打开应用程序时,必须显示下拉值为"three""4th"

就像这样

enter image description here

In my code shared preferences works prefcetly for when I use only one drop down but when I used two or more dropdowns then shows this error.

error

enter image description here

我的代码


class _FamilyDetailsScreenState extends State<FamilyDetailsScreen> {
  // dropdown buttons

  String dropdownValueMembers = 'howmany';

  // List of items in our dropdown menu
  var items = ['howmany', 'one', 'two', 'three  ', 'four    ', '5 or more'];

  void initState() {
    super.initState();
    checkValueMembers();
    checkValueNumber();
  }

  //IF "dropdownValueMembers" is empty pass "howmany" word as a initial value if al ready selected then pass the shared preference value
  checkValueMembers() {
    _getData();
  }

  _saveData(String dropdownValueMembersShared) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString("data", dropdownValueMembersShared);
  }

  _getData() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    dropdownValueMembers = sharedPreferences.getString("data") ?? "howmany";
    setState(() {});
  }

  // data which child
  String dropdownValueNumber = 'which';
//   // List of items in our dropdown menu
  var number = ['which', '1 st', '2 nd', '3 rd  ', '4 th    ', '5 th'];

  //IF "dropdownValueMembers" is empty pass "which" word as a initial value if al ready selected then pass the shared preference value
  checkValueNumber() {
    _getDataNumber();
  }

  _saveDataNumbers(String dropdownValueNumberShared) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString("data2", dropdownValueNumberShared);
  }

  _getDataNumber() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    dropdownValueMembers = sharedPreferences.getString("data2") ?? "which";
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      body: Container(
        child: SafeArea(
          child: Column(
            children: <Widget>[
              const Text(
                'family details',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 18.00,
                  fontWeight: FontWeight.w700,
                ),
              ),
              const SizedBox(
                height: 30,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 10, left: 15),
                child: Row(
                  children: <Widget>[
                    const Icon(
                      Icons.brightness_1,
                      color: Colors.black,
                      size: 10.0,
                    ),
                    const Padding(
                      padding: EdgeInsets.only(left: 13),
                      child: Text(
                        "Number of children",
                        style: TextStyle(
                            fontSize: 15, fontWeight: FontWeight.w600),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 2),
                      child: Container(
                        height: 25,
                        decoration: BoxDecoration(
                          boxShadow: const <BoxShadow>[
                            //apply shadow on Dropdown button
                            BoxShadow(
                                color: Color.fromRGBO(
                                    0, 0, 0, 0.37), //shadow for button
                                blurRadius: 5) //blur radius of shadow
                          ],
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(15),
                        ),
                        child: DropdownButton(
                          underline: Container(),
                          borderRadius: BorderRadius.circular(20),
                          // Initial Value
                          value: dropdownValueMembers,
                          // Down Arrow Icon
                          icon: const Icon(Icons.keyboard_arrow_down),
                          // Array list of items
                          items: items.map((String items) {
                            return DropdownMenuItem(
                              value: items,
                              child: SizedBox(
                                height: 15,
                                width: 120.0, // for example
                                child: Text(items,
                                    style: const TextStyle(
                                        fontSize: 13.0,
                                        fontWeight: FontWeight.w700),
                                    textAlign: TextAlign.center),
                              ),
                            );
                          }).toList(),
                          // After selecting the desired option,it will
                          // change button value to selected value
                          onChanged: (String? newValue) {
                            setState(
                              () {
                                dropdownValueMembers = newValue!;
                              },
                            );
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(
                height: 25,
              ),
              Row(
                children: [
                  Padding(
                    padding: const EdgeInsets.only(left: 20),
                    child: Text('Which child'),
                  ),
                  Padding(
                    padding:
                        const EdgeInsets.only(left: 100, right: 0, top: 20),
                    child: Container(
                      height: 30,
                      decoration: BoxDecoration(
                        boxShadow: const <BoxShadow>[
                          //apply shadow on Dropdown button
                          BoxShadow(
                              color: Color.fromRGBO(
                                  0, 0, 0, 0.37), //shadow for button
                              blurRadius: 5) //blur radius of shadow
                        ],
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(15),
                      ),
                      child: DropdownButton(
                        underline: Container(),
                        borderRadius: BorderRadius.circular(20),
                        // Initial Value
                        value: dropdownValueNumber,
                        // Down Arrow Icon
                        icon: const Icon(Icons.keyboard_arrow_down),
                        // Array list of items
                        items: number.map((String number) {
                          return DropdownMenuItem(
                            value: number,
                            child: SizedBox(
                              height: 17,
                              width: 120.0, // for example
                              child: Text(number,
                                  style: const TextStyle(
                                      fontSize: 13.0,
                                      fontWeight: FontWeight.w700),
                                  textAlign: TextAlign.center),
                            ),
                          );
                        }).toList(),
                        // After selecting the desired option,it will
                        // change button value to selected value
                        onChanged: (String? newNumber) {
                          setState(
                            () {
                              dropdownValueNumber = newNumber!;
                            },
                          );
                        },
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(
                height: 60,
              ),
              Padding(
                padding: const EdgeInsets.only(bottom: 0.0, top: 150),
                child: SizedBox(
                  width: 160.0,
                  height: 35.0,
                  child: ElevatedButton(
                      style: ButtonStyle(
                        shape:
                            MaterialStateProperty.all<RoundedRectangleBorder>(
                          RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(18.0),
                            side: const BorderSide(
                              color: Colors.blueAccent,
                            ),
                          ),
                        ),
                      ),
                      onPressed: () {
                        _saveData(dropdownValueMembers);
                        _saveDataNumbers(dropdownValueNumber);
                      },
                      child: const Text('next')),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

如何解决这一问题,并使用共享首选项保存2个或更多数据?

推荐答案

问题来自于

checkValueNumber() {
    _getDataNumber();
  }

  _getDataNumber() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    dropdownValueMembers = sharedPreferences.getString("data2") ?? "which"; //this
    setState(() {});
  }

which用于第二下拉列表,dropdownValueMembers用作第一下拉列表值.所以它将是

 dropdownValueNumber = sharedPreferences.getString("data2") ?? number.first;

这里还有一些其他的修改

class FamilyDetailsScreen extends StatefulWidget {
  const FamilyDetailsScreen({super.key});

  @override
  State<FamilyDetailsScreen> createState() => _FamilyDetailsScreenState();
}

class _FamilyDetailsScreenState extends State<FamilyDetailsScreen> {
  // 1st dropdown button

  String? dropdownValueMembers;

  // List of items in our dropdown menu
  List<String> items = [
    'howmany',
    'one',
    'two',
    'three  ',
    'four',
    '5 or more'
  ];

  // data which child
  String? dropdownValueNumber;
//   // List of items in our dropdown menu
  List<String> number = ['which', '1 st', '2 nd', '3 rd  ', '4 th    ', '5 th'];

  @override
  void initState() {
    super.initState();
    dropdownValueMembers = items.first;
    dropdownValueNumber = number.first;
    checkValueMembers();
    checkValueNumber();
  }

  checkValueMembers() {
    _getData();
  }

  _saveData(String dropdownValueMembersShared) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString("data", dropdownValueMembersShared);
  }

  _getData() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    dropdownValueMembers = sharedPreferences.getString("data") ?? items.first;
    setState(() {});
  }
  // 2nd dropdown button

  //IF "dropdownValueMembers" is empty pass "which" word as a initial value if al ready selected then pass the shared preference value
  checkValueNumber() {
    _getDataNumber();
  }

  _saveDataNumbers(String dropdownValueNumberShared) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString("data2", dropdownValueNumberShared);
  }

  _getDataNumber() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    dropdownValueNumber = sharedPreferences.getString("data2") ?? number.first;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      body: Container(
        child: SafeArea(
          child: Column(
            children: <Widget>[
              const Text(
                'family details',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 18.00,
                  fontWeight: FontWeight.w700,
                ),
              ),
              const SizedBox(
                height: 30,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 10, left: 15),
                child: Row(
                  children: <Widget>[
                    const Icon(
                      Icons.brightness_1,
                      color: Colors.black,
                      size: 10.0,
                    ),
                    const Padding(
                      padding: EdgeInsets.only(left: 13),
                      child: Text(
                        "Number of children",
                        style: TextStyle(
                            fontSize: 15, fontWeight: FontWeight.w600),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 2),
                      child: Container(
                        height: 25,
                        decoration: BoxDecoration(
                          boxShadow: const <BoxShadow>[
                            //apply shadow on Dropdown button
                            BoxShadow(
                                color: Color.fromRGBO(
                                    0, 0, 0, 0.37), //shadow for button
                                blurRadius: 5) //blur radius of shadow
                          ],
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(15),
                        ),
                        child: DropdownButton(
                          underline: Container(),
                          borderRadius: BorderRadius.circular(20),
                          // Initial Value
                          value: dropdownValueMembers,
                          // Down Arrow Icon
                          icon: const Icon(Icons.keyboard_arrow_down),
                          // Array list of items
                          items: items.map((String data) {
                            return DropdownMenuItem(
                              value: data,
                              child: SizedBox(
                                height: 15,
                                width: 120.0, // for example
                                child: Text(data,
                                    style: const TextStyle(
                                        fontSize: 13.0,
                                        fontWeight: FontWeight.w700),
                                    textAlign: TextAlign.center),
                              ),
                            );
                          }).toList(),
                          // After selecting the desired option,it will
                          // change button value to selected value
                          onChanged: (String? newValue) {
                            setState(
                              () {
                                dropdownValueMembers = newValue!;
                              },
                            );
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(
                height: 25,
              ),
              Row(
                children: [
                  Padding(
                    padding: const EdgeInsets.only(left: 20),
                    child: Text('Which child'),
                  ),
                  Padding(
                    padding:
                        const EdgeInsets.only(left: 100, right: 0, top: 20),
                    child: Container(
                      height: 30,
                      decoration: BoxDecoration(
                        boxShadow: const <BoxShadow>[
                          //apply shadow on Dropdown button
                          BoxShadow(
                              color: Color.fromRGBO(
                                  0, 0, 0, 0.37), //shadow for button
                              blurRadius: 5) //blur radius of shadow
                        ],
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(15),
                      ),
                      child: DropdownButton(
                        underline: Container(),
                        borderRadius: BorderRadius.circular(20),
                        // Initial Value
                        value: dropdownValueNumber,
                        // Down Arrow Icon
                        icon: const Icon(Icons.keyboard_arrow_down),
                        // Array list of items
                        items: number.map((String number) {
                          return DropdownMenuItem(
                            value: number,
                            child: SizedBox(
                              height: 17,
                              width: 120.0, // for example
                              child: Text(number,
                                  style: const TextStyle(
                                      fontSize: 13.0,
                                      fontWeight: FontWeight.w700),
                                  textAlign: TextAlign.center),
                            ),
                          );
                        }).toList(),
                        // After selecting the desired option,it will
                        // change button value to selected value
                        onChanged: (String? newNumber) {
                          setState(
                            () {
                              dropdownValueNumber = newNumber!;
                            },
                          );
                        },
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(
                height: 60,
              ),
              Padding(
                padding: const EdgeInsets.only(bottom: 0.0, top: 150),
                child: SizedBox(
                  width: 160.0,
                  height: 35.0,
                  child: ElevatedButton(
                      style: ButtonStyle(
                        shape:
                            MaterialStateProperty.all<RoundedRectangleBorder>(
                          RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(18.0),
                            side: const BorderSide(
                              color: Colors.blueAccent,
                            ),
                          ),
                        ),
                      ),
                      onPressed: () {
                        //do null check 1st
                        _saveData(dropdownValueMembers!);
                        _saveDataNumbers(dropdownValueNumber!);
                      },
                      child: const Text('next')),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Flutter相关问答推荐

允许冻结在初始化时使用工厂

在Flutter 中创建自定义Snackbar类

为什么PUT方法没有发出任何响应?

框中的Flutter 适配图像

无法将新文物与Flutter 项目集成在一起

为什么用户界面不会在Flight中的复选框中更改?

在创建显示此错误的Flutter 深度链接时

顶部对齐ListTile的[前导、标题、尾随]小部件

从Firestore流式传输单个文档还是整个集合更好?

Flutter 构建 Web 分段故障 - 无法启动事件处理程序线程

Flutter:在 pubspec.yaml 中找不到assets资源

没有为类型 'Widget' 定义运算符 '[]' .try 定义运算符[]

在 Flutter 中解码 BLE 设备负载

如何设置行中项目之间的空格相等?

如何在 flutter 中使用带有有效负载数据的重定向来执行 firebase 推送通知.?

Flutter Bloc 使用 Cubit 监听流和emits 状态

如何验证非表单字段?

Firebase 中的查询限制 - .orderBy() 错误

带图像封面的 ElevatedButton

在另一个页面编辑数据后更新 Flutter 页面的惯用方法?