我的缓存类
import 'dart:async';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class CacheUtil{
static set(String key, value) async{
if(value is Map || value is List){
value = json.encode(value);
}
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.setString(key, json.encode(value));
}
static get(String key) async{
SharedPreferences preferences = await SharedPreferences.getInstance();
String data = preferences.getString(key);
return data;
}
}
在get方法中,我想看看value是否可以是json.decode 我该怎么办?
答案 0 :(得分:2)
只需尝试对其进行解码并捕获FormatException
即可知道它何时失败:
void main() {
var jsonString = '{"abc'
Map<String,dynamic> decodedJSON;
var decodeSucceeded = false;
try {
var x = json.decode(jsonString) as Map<String, dynamic>;
decodeSucceeded = true;
} on FormatException catch (e) {
print('The provided string is not valid JSON');
}
print('Decoding succeeded: $decodeSucceeded');
}