无法更新实时数据库中的数据

Unable to update data in Realtime Database

所以我目前在 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);
  }
}

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

我该如何解决这个问题?

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

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