Search code examples
flutterdartfirebase-realtime-databasegoogle-cloud-firestoresharedpreferences

how can i store multiple data in sharedpreferences?


I am getting user information like the username , profile pic and name .I want to store all that info inside Sharedpreferences so that i wont have to call firebase every time I need them. here is how i am getting the data ,how can i store this data so that later on i can get user's name and its profilepic by checking it through its username ?

storeUsersInfo()async{
    print('STORE CALLED');
    QuerySnapshot querySnapshot = await DatabaseMethods().getUsers();
    var length = querySnapshot.docs.length ;
      print(length);
      int i = 0 ;
    while (  i < length ) {
      print(name = "${querySnapshot.docs[i]["name"]}");
      print(profilePicUrl = "${querySnapshot.docs[i]["profileURL"]}");
      i++;

    }
  }

here is the firebase call

 Future<QuerySnapshot> getUsers() async {
    return await FirebaseFirestore.instance
        .collection("users")
        .get();
  }

and if anyone needs anything else please ask .


Solution

  • You can store all the information in SharePreference by encoding picture objects to Base64String before storing them.

    How you can encode it:

    Future<String> encodeImageToBase64String(String imageUrl) async {
      
      final response = await client.get(Uri.parse(imageUrl));
     
      final base64 = base64Encode(response.bodyBytes);
    
      return base64;
    }
    

    After Encoding the image, you can cache it to sharedPreference using

    SharedPreferences pref = await SharedPreferences.getInstance();
    
    //Save string to SharedPreference
    pref.setString('image', encodedImageString);
    
    

    How to Decode and use Image Later

    //Get Encoded Image String from SharedPreferences
    final base64String = pref.getString('image');
    
    ///Decodes Images file encoded to Base64String to Image
    Uint8List decodeImageFromBase64String(String base64String) {
      return base64Decode(base64String);
    }
    
    

    Finally, you can use this in your Image Widget like so

    ...
    Image(image: MemoryImage(decodeImageFromBase64String))
    
    

    Assuming you want to cache name, username and image gotten from firebase

    //Create a model for the firebase data
    class UserModel{
      final String name;
      final String username;
      final String encodedImage;
      
      UserModel(this.name, this.username, this.encodedImage);
      
      String toJson(){
        Map<String, dynamic> userMap = {
          'name': name,
          'username': username,
          'image': encodedImage,
        };
        
        return json.encode(userMap);
      }
    }
    
    //Encode the image HERE
    encodeImageToBase64String(imageUrl);
     
    //Pass in the parameters to the UserModel() constructor and Call //the toJson(), then Cache the Resulting String
    String stringToCache = UserModel(nameString, usernameString, encodedImageString).toJson();