面试题答案
一键面试- 将类实例转换为适合存储的格式:
- 步骤:
- 在 Dart 类中,实现
toJson
方法,将对象的属性转换为 JSON 可序列化的格式。因为SharedPreferences
一般存储字符串,所以将对象转换为 JSON 字符串比较合适。
- 在 Dart 类中,实现
- 关键代码片段:
- 步骤:
class MyCustomClass {
String stringProp;
int intProp;
bool boolProp;
MyCustomClass({
required this.stringProp,
required this.intProp,
required this.boolProp,
});
Map<String, dynamic> toJson() {
return {
"stringProp": stringProp,
"intProp": intProp,
"boolProp": boolProp,
};
}
}
- 存储转换后的格式到 SharedPreferences:
- 步骤:
- 导入
package:shared_preferences/shared_preferences.dart
库。 - 获取
SharedPreferences
实例。 - 将 JSON 字符串存储到
SharedPreferences
中。
- 导入
- 关键代码片段:
- 步骤:
import 'package:shared_preferences/shared_preferences.dart';
Future<void> saveToSharedPreferences(MyCustomClass obj) async {
final prefs = await SharedPreferences.getInstance();
final jsonString = jsonEncode(obj.toJson());
await prefs.setString('my_custom_obj', jsonString);
}
- 从 SharedPreferences 读取并转换回原类实例:
- 步骤:
- 从
SharedPreferences
读取存储的 JSON 字符串。 - 将 JSON 字符串解码为
Map<String, dynamic>
。 - 使用解码后的
Map
数据创建原类的实例。
- 从
- 关键代码片段:
- 步骤:
Future<MyCustomClass?> readFromSharedPreferences() async {
final prefs = await SharedPreferences.getInstance();
final jsonString = prefs.getString('my_custom_obj');
if (jsonString == null) {
return null;
}
final jsonMap = jsonDecode(jsonString) as Map<String, dynamic>;
return MyCustomClass(
stringProp: jsonMap['stringProp'],
intProp: jsonMap['intProp'],
boolProp: jsonMap['boolProp'],
);
}
这里假设已经导入了 dart:convert
库用于 JSON 编码和解码。同时,SharedPreferences
操作是异步的,所以相关方法都使用了 Future
。