作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我想知道将数据保存到我的模型中的最佳方法是什么。我注意到关于 StreamBuilder 和模型的信息并没有太多。 (我的意思是两者都在一起)。
这是我目前的模型。
class User {
String _username, _name, _dateBorn, _gender;
bool _isObserver, _notifyFriends, _recordAudio, _sendTweet;
List<dynamic> _friendList;
List<dynamic> _pendingFriends;
User(
this._username,
this._name,
this._dateBorn,
this._gender,
this._isObserver,
this._notifyFriends,
this._recordAudio,
this._sendTweet,
this._friendList,
this._pendingFriends);
String get username => _username;
String get name => _name;
String get dateBorn => _dateBorn;
String get gender => _gender;
bool get isObserver => _isObserver;
bool get notifyFriends => _notifyFriends;
bool get recordAudio => _recordAudio;
bool get sendTweet => _sendTweet;
set setNotifyFriends(bool value) => _notifyFriends = value;
set setRecordAudio(bool value) => _recordAudio = value;
set setSendTweet(bool value) => _sendTweet = value;
List<dynamic> get friendList => _friendList;
List<dynamic> get pendinFriends => _pendingFriends;
}
这是我当前的 FireStore 数据库。
StreamBuilder(
stream:
FirebaseFirestore.instance.collection('Usuarios').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
var data = snapshot.data!.docs;
var user;
data.forEach((element) {
if (element["username"] == me) {
user = User(
element["username"],
element["realName"],
element["date_birth"],
element["sexo"],
element["isObserver"],
element["config"]["notifyFriends"],
element["config"]["recordAudio"],
element["config"]["sendTweet"],
element["friends"],
element["pendingFriends"],
);
}
});
return FriendsWidget(user);
}),
但我很确定这不是一个好的做法,将数据提供给模型的最佳做法是什么?在不丢失实时更新数据功能的情况下?
最佳答案
We can make use of
json_serializable
package available inFlutter to ease the JSON parsing and assign it to respective modelclass instead of assigning it manually.
fromJson
和
toJson
解析 JSONObjects。但是,我们可能需要设置一些开发依赖项才能使其在我们的项目中工作。请参阅
Flutter 处的文档
FirebaseFirestore.instance.collection('allUsers').snapshots().listen((event) {
for (var element in event.docChanges) {
final modelData = UserModel.fromJson(element.doc.data());
// Do anything with your user. For example adding to list.
}
});
模型类
part 'user_model.g.dart';
@JsonSerializable()
class UserModel {
@JsonKey(name: 'user_id')
String userId;
@JsonKey(name: 'name')
String name;
UserModel();
factory UserModel.fromJson(Map<String, dynamic> json) => _$UserModelFromJson(json);
Map<String, dynamic> toJson() => _$UserModelToJson(this);
}
json_serializable
的用法与
firestore
在以下文章中进行了解释。把它作为引用。
关于flutter - 如何从 StreamBuilder 将数据正确保存到我的模型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68542604/
我是一名优秀的程序员,十分优秀!