Home > Software design >  Tried to add shared Preference to dropdown value but shows this error "The argument type '
Tried to add shared Preference to dropdown value but shows this error "The argument type '

Time:10-22

I used shared preference dependency to my project.At the initially open app dropdown value must be 'howmany' but when select any other value and click next button and close application from mobile recents and user when reopen again then should display the value selected value by the user.

Ex:- At the initially user open app then dropdown value must be 'howmany' and he select "three" 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"

images initial value

enter image description here

And according to this scenario, I tried to code but then shows these errors. 1st error

enter image description here

2nd error

enter image description here

MY code

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class FamilyDetailsScreen extends StatefulWidget {
  @override
  State<FamilyDetailsScreen> createState() => _FamilyDetailsScreenState();
}

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

  late String dropdownValueMembersShared;

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

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

  //IF "dropdownValueMembers" is empty pass "howmany" word as a initial value if al ready selected then pass the shared preference value
  checkValueMembers() {
    if (dropdownValueMembersShared != false) {
      // Initial Selected Value  Members
      String dropdownValueMembers = 'howmany';
    } else {
      String dropdownValueMembers = dropdownValueMembersShared;
    }
  }

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

  @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,
              ),
              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;
                      },
                      child: const Text('next')),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

How to solve these errors and How to adding sharedpreference to this code help me......

CodePudding user response:

try this

  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();
  }

  //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(() {});
  }

  @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,
              ),
              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);
                      },
                      child: const Text('next')),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

CodePudding user response:

In your checkValueMembers method you should have it check to be

dropdownValueMembersShared == ''

You currently check and assume it is a boolean type when it is a string. You also need to only set it to howmany when it's empty, and then default to the value if there is one, which your current statement does not do.

  • Related