【问题标题】:Unable to update data in Realtime Database无法更新实时数据库中的数据
【发布时间】:2021-12-23 00:16:36
【问题描述】:

所以我目前在 Firebase 中有一个数据库,其中包含我向用户显示的信息。作为管理员,我想更新信息。但是,当我尝试更新它时,会在 Firebase 实时数据库中添加一条新记录。

这是显示实时数据库中所有记录的代码以及将其重定向到更新页面的编辑图标:

class _UpdateDestinationsState extends State<UpdateDestinations> {
  final destdatabaseref = FirebaseDatabase.instance
      .reference()
      .child('Database')
      .child('DestinationsandActivities')
      .orderByChild("category")
      .equalTo("Destination");

  @override
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.white), //add this line here
        backgroundColor: Color(0xFF3d5a89),
        elevation: 0,
        centerTitle: true,
        title: const Text('Update Destinations',
            style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w500,
                color: Colors.white)),
      ),
      body: SafeArea(
          child: FirebaseAnimatedList(
              query: destdatabaseref,
              itemBuilder: (BuildContext context, DataSnapshot snapshot,
                  Animation<double> animation, int index) {
                return ListTile(
                  title: Text(snapshot.value['name']),
                  trailing: IconButton(
                      onPressed: () {
                        Navigator.of(context).push(MaterialPageRoute(
                            builder: (context) => UpdatePage(
                                  name: snapshot.value['name'],
                                  description: snapshot.value['description'],
                                  id: snapshot.value['id'],
                                )));
                      },
                      icon: Icon(Icons.edit)),
                );
              })),
    );
  }
}

这是更新页面的代码,您可以在其中编辑信息:

class UpdatePage extends StatefulWidget {
  final String name;
  final String description;
  final String id;

  UpdatePage(
      {Key? key,
      required this.name,
      required this.description,
      required this.id})
      : super(key: key);

  @override
  _UpdatePageState createState() => _UpdatePageState();
}

class _UpdatePageState extends State<UpdatePage> {
  final destdatabaseref = FirebaseDatabase.instance
      .reference()
      .child('Database')
      .child('DestinationsandActivities');

  @override
  Widget build(BuildContext context) {
    final nameController = TextEditingController();
    final descriptionController = TextEditingController();

    setState(() {
      nameController.text = widget.name;
      descriptionController.text = widget.description;
    });
    return Scaffold(
        appBar: AppBar(
          iconTheme: IconThemeData(color: Colors.white),
          backgroundColor: Color(0xFF3d5a89),
          elevation: 0,
          centerTitle: true,
          title: const Text('Update Destinations',
              style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w500,
                  color: Colors.white)),
        ),
        body: Form(
          child: Padding(
            padding: EdgeInsets.all(8),
            child: Column(
              children: [
                TextFormField(
                  controller: nameController,
                  autofocus: false,
                  decoration: InputDecoration(
                    labelText: 'Name',
                    border: OutlineInputBorder(),
                  ),
                ),
                SizedBox(height: 10),
                TextFormField(
                  controller: descriptionController,
                  autofocus: false,
                  decoration: InputDecoration(
                    labelText: 'Description',
                    border: OutlineInputBorder(),
                  ),
                ),
                TextButton(
                    onPressed: () {
                      updateData(widget.name, widget.description, widget.id);
                      Navigator.pop(context);
                    },
                    child: Text('Update')),
                TextButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text('Cancel')),
              ],
            ),
          ),
        ));
  }

  void updateData(String name, String description, var key) {
    Map<String, String> newvalue = {'name': name, 'description': description};
    destdatabaseref.child(key).update(newvalue);
  }
}

使用此代码,当我单击更新文本按钮时,我会将此类记录添加到我的实时数据库中:

我该如何解决这个问题?

【问题讨论】:

    标签: firebase flutter dart firebase-realtime-database


    【解决方案1】:

    我认为问题在于获取 id。
    如果您传递空值,Realtime 将使用生成的密钥(id),我之前从未使用过 FirebaseAnimatedList,但我看到了一个示例,他们使用 snapshot.key 访问密钥....
    但我确定它不是 snapshot.value['id'],因为在您的结构中没有带有名称和装饰的 id,它将作为对象返回,因此 id 不会是访问它的字段。
    因此,首先尝试打印 snapshot.value['id'] 如果它包含 id 然后跳过我的答案,如果它为 null 尝试 snapshot.key,如果这也不起作用,请查看如何使用 FirebaseAnimatedList 构建快照。

    【讨论】:

    • 嘿,谢谢!我认为这可能会奏效。但是,我将snapshot.key 声明为UpdatePage 类中的var 而不是最终字符串,我得到“This class (or a class that this class inherits from) is marked as '@immutable', but one or more of its instance fields aren't final: UpdatePage.id
    • 您不需要这样做,保持UpdatePage 类不变,只需将您传递的内容更改为:onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) =&gt; UpdatePage( name: snapshot.value['name'], description: snapshot.value['description'], id: snapshot.key, //&lt;-- here ))); },
    • 我这样做了,但它说The argument type 'String?' can't be assigned to the parameter type 'String'
    • 我不知道你是否知道那是什么意思,但它与空安全有关,在哪里?意味着该字符串可以为空,如果您不添加它,则该值不能为空,这就是这里发生的情况,其中 UpdatePage 不能为其任何参数取空值。要解决这个问题,有多种简单的方法: - (不好)允许 UpdatePage 通过使用 '?' 来获取空值:final String? id; 这不好,因为您需要 id。 - 在调用它之前检查值:onPressed:() { if(snapshot.key!=null){Navigator.of(context)...}更多检查(并停止错误)传递:snapshot.key??''
    • 我试过了!绝对消除The argument type 'String?' can't be assigned to the parameter type 'String' 错误,但数据仍然无法更新。
    【解决方案2】:

    我终于找到了错误。 updateData(widget.name, widget.description, widget.id); 应该是:updateData(nameController.text, descriptionController.text, widget.id);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 2019-04-27
      • 2015-07-03
      相关资源
      最近更新 更多