如果您只在设备上存储这一项,我会选择共享首选项。为您的用户类fromMap、toMap、fromJson、toJson 提供辅助方法很容易。当您想存储在共享首选项中时,您调用toJson 将其转换为字符串。当您想将其转换回用户类时,您只需调用 fromJson,它会从 Shared Preferences 中获取字符串并返回一个 User 实例。
当然,您可以使用 Hive 并为您完成这项工作,但 IMO 这样做有点矫枉过正。
用户类别:
import 'dart:convert';
class User {
final String uid;
final String fullname;
final String email;
final String domicile;
final String profilePicturePath;
final bool verified;
final bool banned;
List<String> attendedEventIDs;
List<String> followingUserIDs;
final int numberOfFollowers;
final int numberOfApprovedEvents;
final String description;
final List<Event> upcomingEvents;
User({
this.uid,
this.fullname,
this.email,
this.domicile,
this.profilePicturePath,
this.verified,
this.banned,
this.attendedEventIDs,
this.followingUserIDs,
this.numberOfFollowers,
this.numberOfApprovedEvents,
this.description,
this.upcomingEvents,
});
Map<String, dynamic> toMap() {
return {
'uid': uid,
'fullname': fullname,
'email': email,
'domicile': domicile,
'profilePicturePath': profilePicturePath,
'verified': verified,
'banned': banned,
'attendedEventIDs': attendedEventIDs,
'followingUserIDs': followingUserIDs,
'numberOfFollowers': numberOfFollowers,
'numberOfApprovedEvents': numberOfApprovedEvents,
'description': description,
'upcomingEvents': upcomingEvents?.map((x) => x.toMap())?.toList(),
};
}
factory User.fromMap(Map<String, dynamic> map) {
return User(
uid: map['uid'],
fullname: map['fullname'],
email: map['email'],
domicile: map['domicile'],
profilePicturePath: map['profilePicturePath'],
verified: map['verified'],
banned: map['banned'],
attendedEventIDs: List<String>.from(map['attendedEventIDs']),
followingUserIDs: List<String>.from(map['followingUserIDs']),
numberOfFollowers: map['numberOfFollowers'],
numberOfApprovedEvents: map['numberOfApprovedEvents'],
description: map['description'],
upcomingEvents: List<Event>.from(map['upcomingEvents']?.map((x) => Event.fromMap(x))),
);
}
String toJson() => json.encode(toMap());
factory User.fromJson(String source) => User.fromMap(json.decode(source));
}