MST
星途 面试题库

面试题:Flutter中SharedPreferences在复杂场景下的定制与扩展

假设你正在开发一个具有复杂用户配置功能的Flutter应用,用户配置数据不仅包含简单的字符串、数字等类型,还涉及到自定义对象和嵌套结构的数据。请详细说明如何基于SharedPreferences进行定制化扩展,以满足这种复杂场景下的数据存储和读取需求,包括数据结构设计、序列化与反序列化方法等。
18.2万 热度难度
前端开发Flutter

知识考点

AI 面试

面试题答案

一键面试

1. 数据结构设计

  • 顶层结构:将用户配置数据封装在一个主配置类中,例如 UserConfig 类。
class UserConfig {
  String? username;
  int? age;
  CustomObject? customObj;
  List<NestedObject>? nestedList;

  UserConfig({this.username, this.age, this.customObj, this.nestedList});
}
  • 自定义对象类:定义 CustomObjectNestedObject 等自定义类来表示嵌套结构数据。
class CustomObject {
  String? property1;
  double? property2;

  CustomObject({this.property1, this.property2});
}

class NestedObject {
  int? id;
  String? name;

  NestedObject({this.id, this.name});
}

2. 序列化方法

  • 使用JSON序列化:利用 dart:convert 库将对象转换为JSON字符串进行存储。
import 'dart:convert';

extension UserConfigSerialization on UserConfig {
  String toJsonString() {
    return json.encode({
      'username': username,
      'age': age,
      'customObj': customObj == null? null : {
        'property1': customObj!.property1,
        'property2': customObj!.property2
      },
      'nestedList': nestedList == null? null : nestedList!.map((n) => {
        'id': n.id,
        'name': n.name
      }).toList()
    });
  }
}

extension CustomObjectSerialization on CustomObject {
  Map<String, dynamic> toJson() {
    return {
      'property1': property1,
      'property2': property2
    };
  }
}

extension NestedObjectSerialization on NestedObject {
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name
    };
  }
}

3. 反序列化方法

  • 从JSON字符串还原对象:同样利用 dart:convert 库从JSON字符串解析出对象。
extension UserConfigDeserialization on UserConfig {
  static UserConfig fromJsonString(String jsonString) {
    Map<String, dynamic> jsonMap = json.decode(jsonString);
    return UserConfig(
      username: jsonMap['username'],
      age: jsonMap['age'],
      customObj: jsonMap['customObj'] == null? null : CustomObject(
        property1: jsonMap['customObj']['property1'],
        property2: jsonMap['customObj']['property2']
      ),
      nestedList: jsonMap['nestedList'] == null? null : (jsonMap['nestedList'] as List).map((n) => NestedObject(
        id: n['id'],
        name: n['name']
      )).toList()
    );
  }
}

4. 基于SharedPreferences的存储和读取

  • 存储:在 SharedPreferences 中以字符串形式存储序列化后的用户配置数据。
import 'package:shared_preferences/shared_preferences.dart';

Future<void> saveUserConfig(UserConfig config) async {
  final prefs = await SharedPreferences.getInstance();
  String jsonString = config.toJsonString();
  await prefs.setString('user_config', jsonString);
}
  • 读取:从 SharedPreferences 读取字符串并反序列化为用户配置对象。
Future<UserConfig?> loadUserConfig() async {
  final prefs = await SharedPreferences.getInstance();
  String? jsonString = prefs.getString('user_config');
  if (jsonString != null) {
    return UserConfig.fromJsonString(jsonString);
  }
  return null;
}