skip to Main Content

How to pass the parameter getString need String? but read() used String

class SharedPref {
  read(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return json.decode(prefs.getString(key)); // the error in this line
  }

this is for sharedPreferences of flutter. how to solve this?

4

Answers


  1. The line prefs.getString(key) returns a String?. It means that can return a String or a null value. You have to ensure that the value will not be null when passed to json.decode().

    Check out the documentation for more info.

    Login or Signup to reply.
  2. Try this:

    return json.decode(prefs.getString(key) ?? '');
    // or
    return prefs.getString(key) != null ? json.decode(prefs.getString(key)) : '';
    
    Login or Signup to reply.
  3. Update your code

    read(String key) async {
        final prefs = await SharedPreferences.getInstance();
        String? str = prefs.getString(key) ?? '';
        return json.decode(str); 
    }
    
    Login or Signup to reply.
  4. It’s cause of getString method have return type String?

      /// Reads a value from persistent storage, throwing an exception if it's not a
      /// String.
      String? getString(String key) => _preferenceCache[key] as String?;
    

    But json.decode takes String as parameter

      /// Parses the string and returns the resulting Json object.
      ///
      /// The optional [reviver] function is called once for each object or list
      /// property that has been parsed during decoding. The `key` argument is either
      /// the integer list index for a list property, the string map key for object
      /// properties, or `null` for the final result.
      ///
      /// The default [reviver] (when not provided) is the identity function.
      dynamic decode(String source,
          {Object? reviver(Object? key, Object? value)?}) {
        reviver ??= _reviver;
        if (reviver == null) return decoder.convert(source);
        return JsonDecoder(reviver).convert(source);
      }
    

    So you must pass String into json.decode method. There are many ways to do this

    // prefs.getString(key) return null, use '' as parameter
    return json.decode(prefs.getString(key) ?? ''); 
    // or
    // throw exception when prefs.getString(key) return null. 
    // Wrap your method with `try ... catch ... `
    return json.decode(prefs.getString(key)!); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search