Home > database >  Tried to add shared Preference for two dropdown values but shows then error "Failed assertion:
Tried to add shared Preference for two dropdown values but shows then error "Failed assertion:

Time:10-23

this is my output but when I add shared preference then shows an error as I mention below.

enter image description here

I used shared preference dependency in my project. At the initially open app 1st dropdown value must be 'howmany' and 2nd dropdown value 'which' but when selecting any other value and click the next button and closing the application from mobile recents and the user when reopening again then should display the value selected values by the user.

Ex:- At the initially user open app then 1st dropdown value must be 'howmany' , 2nd 'which' and he select 1st dropdown "three" , 2nd dropdown "4th" and click next button after close the app and remove from recents apps. Later when he reopen the app must display dropdown value is "three" and "4th"

like this

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

My code


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')),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

How solve this and save 2 or more data using shared preferences?

CodePudding user response:

The issue coming from

checkValueNumber() {
    _getDataNumber();
  }

And

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

which is been used on second dropdown and dropdownValueMembers as 1st dropdown value. So the it will be

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

There are some other modification here

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')),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
  • Related