【问题标题】:Flutter firebase database.set(object) issueFlutter firebase database.set(object)问题
【发布时间】:2019-06-04 00:40:38
【问题描述】:

我有一个类 Product,它在 List plist 中 现在我需要调用 firebase database.set(plist) 这正在使用 Java,但是当我尝试使用 Flutter dart 进行操作时,它显示错误任何人都有解决此问题的方法 从 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());
      });
    }
  });
}

【问题讨论】:

  • 发布您的代码/错误
  • 更新了请查收
  • 请发布您的代码。
  • 更新了请查收
  • @Slick Slime,是的。与 Java SDK 不同的是,在 Flutter 中,您必须进行“从/到”映射。可以保存List,它会变成数据库中的一个数组,但是要小心使用。

标签: firebase firebase-realtime-database dart flutter flutter-dependencies


【解决方案1】:

我们不能直接在 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;
});

}

我希望这段代码会有所帮助。

【讨论】:

    【解决方案2】:

    稍微扩展上面作为评论给出的答案

    你基本上必须事先创建一个辅助地图:

    Map aux = new Map<String,dynamic>();
    

    然后遍历数组,为每个要添加的子元素添加相应的映射:

     productList.forEach((product){
        //Here you can set the key of the map to whatever you like
        aux[product.id] = product.toMap();
     });
    

    以防万一,Product 类中的 toMap 函数应该是这样的:

    Map toMap() {
      Map toReturn = new Map();
      toReturn['id'] = id;
      toReturn['name'] = name;
      toReturn['description'] = description;
      return toReturn;
    }
    

    然后,当您调用 set 函数保存到 firebase 时,您可以执行以下操作:

    .set({'productList':aux,})
    

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 2022-01-22
      • 2021-11-22
      • 2020-06-29
      • 1970-01-01
      • 2020-04-01
      • 2021-04-04
      • 2022-01-16
      • 2020-10-13
      相关资源
      最近更新 更多