skip to Main Content

I have next piece of flutter code, to get shared preference key-value

I do understand why _blueUriInit is always NULL

enter image description here

3

Answers


  1. I assume that you are forgot to provide the value for that key before call to get its value, you need to first assign value to it first:

    Future<bool> saveData(String key, dynamic value) async {
      final prefs = await SharedPreferences.getInstance();
      return prefs.setString(key, value);
    }
    

    and call it like this:

    void initState() {
       saveData('blueUri', 'test');
    
       setState(() {
         _blueUriInit = getValue('blueUri');
       });
       super.initState();
    }
    

    now next time you open your app, getValue should return you test.

    Login or Signup to reply.
  2. you can create this function for setting value

    static setUserID(String key, String value) async {
       final SharedPreferences preferences = await SharedPreferences.getInstance();
       preferences.setString(key, value);
    }
    

    Use case :

    await SharedValue.setUserID("Email", "[email protected]");
    

    And For getting value from shared preference you can use this function

    static Future<String?> getUserID(String key) async {
        final SharedPreferences preferences = await SharedPreferences.getInstance();
        return preferences.getString(key);
    }
    

    Use case :

    userName = await SharedValue.getUserID("Email");
    
    Login or Signup to reply.
  3. First you need to setString with key and value (name is key)

    Future setValue() async {
      final prefs = await SharedPreferences.getInstance();
      prefs.setString("name", "Hitarth");
    }
    

    getString with key (here i took "name" as key)

    Future getValue(String key) async {
      final prefs = await SharedPreferences.getInstance();
      String value = prefs.getString(key) ?? "NULL";
      return value;
    }
    

    store in variable callin getValue

    void initState() {
      setState(() {
        _blueUriInit = getValue("name");
      });
      super.initState();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search