taha khamis
taha khamis

Reputation: 567

How to retrieve multiple values from shared preferences at once in flutter

I am saving some values to share preferences when the user register for the first time. When I need these values, I am calling them with this function:

Future <String> getUserInfo() async{
  SharedPreferences preferences = await SharedPreferences.getInstance();
     String username = preferences.getString('$userID,name')?? "No name found";
     String weight = preferences.getString('$userID,weight') ?? "no wight found";
     String height = preferences.getString('$userID,height') ?? "no Height found";
     String gendertype = preferences.getString('$userID,genderType') ?? "no gender Type found";
       userName = username;
       userWeight = weight;
       userHeight = height;
       userGender = gendertype;
  return username;
  }

After that I am using future builder to show the values I want.


Widget userValues(){
    return
      FutureBuilder<String>(
        future: getUserInfo(),
        builder: (BuildContext context, AsyncSnapshot<String> snapshot){
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return Center(
                child: Text(
                  '${snapshot.error} occurred',
                  style: const TextStyle(fontSize: 18),
                ),
              );
            } else if (snapshot.hasData) {
              return Column(
                children: [
                  Text(userName!),
                  Text(userWeight!),
                  Text(userHeight!),
                  Text(userGender!),
                ],
              );
            }
          }
          return const Center(
            child: CircularProgressIndicator(),
          );
        },
      );
  }

This approach is working totally fine with me but I still feel like this is not the best way to do it and it can be improved. Anyone have any suggestions on how to improve this code?

Thanks in advance.

Upvotes: 1

Views: 434

Answers (1)

Gaspard Merten
Gaspard Merten

Reputation: 1233

One way to simplify your process would be as follow.

  1. Start by implementing two methods (toJson -> Map and fromJson(Map JSON)) in a class named User. In that class, you add all the fields related to the user model.

  2. Instead of storing each value independently, you store the serialised object (using to JSON) with the key "user". Then when you want to retrieve its value, you retrieve the "user" key and parse it using User.fromJson.

If you want to learn more about serialization, here is a neet resource: https://docs.flutter.dev/development/data-and-backend/json

Upvotes: 2

Related Questions