dart Flutter:参数类型'String?无法将'分配给SharedPreference中的参数类型'String'

ve7v8dk2  于 2023-07-31  发布在  Flutter
关注(0)|答案(4)|浏览(137)

如何传递参数getString需要String?但read()使用的字符串

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

字符串
这是用于Flutter共享首选项。如何解决这个问题呢?

qpgpyjmq

qpgpyjmq1#

试试这个:

return json.decode(prefs.getString(key) ?? '');
// or
return prefs.getString(key) != null ? json.decode(prefs.getString(key)) : '';

字符串

ws51t4hk

ws51t4hk2#

prefs.getString(key)返回一个String?。这意味着可以返回一个String或null值。必须确保传递给json.decode()时该值不会为空。
查看documentation以了解更多信息。

pgvzfuti

pgvzfuti3#

更新代码

read(String key) async {
    final prefs = await SharedPreferences.getInstance();
    String? str = prefs.getString(key) ?? '';
    return json.decode(str); 
}

字符串

35g0bw71

35g0bw714#

这是因为getString方法的返回类型为String?

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

字符串
json.decodeString为参数

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


因此,必须将String传入json.decode方法。有很多方法可以做到这一点

// 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)!);

相关问题