class SharedPref {
read(String key) async {
final prefs = await SharedPreferences.getInstance();
return json.decode(prefs.getString(key)); // the error in this line
}
/// Reads a value from persistent storage, throwing an exception if it's not a
/// String.
String? getString(String key) => _preferenceCache[key] as String?;
字符串 但json.decode以String为参数
/// 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)!);
4条答案
按热度按时间qpgpyjmq1#
试试这个:
字符串
ws51t4hk2#
行
prefs.getString(key)
返回一个String?
。这意味着可以返回一个String或null值。必须确保传递给json.decode()
时该值不会为空。查看documentation以了解更多信息。
pgvzfuti3#
更新代码
字符串
35g0bw714#
这是因为
getString
方法的返回类型为String?
字符串
但
json.decode
以String
为参数型
因此,必须将
String
传入json.decode
方法。有很多方法可以做到这一点型