Mid*_*laj 4 dart firebase firebase-realtime-database flutter flutter-dependencies
我有一个 Product 类,它在 List plist 中StackOverflow,我理解使用 database.set('{"a":"apple"}) 但是当我处理 List 时我不能使用这个解决方案
更新错误信息
错误称为无效参数:“产品”实例
我的代码
String table_name="order";
FirebaseAuth.instance.currentUser().then((u){
if(u!=null){
FirebaseDatabase database = FirebaseDatabase(app: app);
String push=database.reference().child(table_name).child(u.uid).push().key;
database.reference().child(table_name).child(u.uid).child(push).set( (productList)).then((r){
print("order set called");
}).catchError((onError){
print("order error called "+onError.toString());
});
}
});
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我们不能直接在 Firebase 中设置对象。不幸的是,在 Flutter 中没有像 java json 这样简单的解决方案。允许的数据类型有 String、boolean、int、double、Map、List。在database.set() 里面。
我们可以看看 Flutter 的官方文档https://pub.dev/documentation/firebase_database/latest/firebase_database/DatabaseReference/set.html
尝试像这样设置对象
Future<bool> saveUserData(UserModel userModel) async {
await _database
.reference()
.child("Users")
.child(userModel.username)
.set(<String, Object>{
"mobileNumber": userModel.mobileNumber,
"userName": userModel.userName,
"fullName": userModel.fullName,
}).then((onValue) {
return true;
}).catchError((onError) {
return false;
});
Run Code Online (Sandbox Code Playgroud)
}
我希望这段代码会有所帮助。
稍微扩展一下上面评论中给出的答案
你基本上必须事先创建一个辅助地图:
Map aux = new Map<String,dynamic>();
Run Code Online (Sandbox Code Playgroud)
然后迭代您为要添加的每个子项添加相应映射的数组:
productList.forEach((product){
//Here you can set the key of the map to whatever you like
aux[product.id] = product.toMap();
});
Run Code Online (Sandbox Code Playgroud)
以防万一,Product 类中的 toMap 函数应该类似于:
Map toMap() {
Map toReturn = new Map();
toReturn['id'] = id;
toReturn['name'] = name;
toReturn['description'] = description;
return toReturn;
}
Run Code Online (Sandbox Code Playgroud)
然后,当您调用 set 函数来保存到 firebase 时,您可以执行以下操作:
.set({'productList':aux,})
Run Code Online (Sandbox Code Playgroud)
希望这对某人有帮助。
归档时间: |
|
查看次数: |
3150 次 |
最近记录: |