【问题标题】:Flutter: Realtime database, append data under specific UIDFlutter:实时数据库,在特定UID下追加数据
【发布时间】:2021-04-28 01:23:51
【问题描述】:

我试图在每次点击实时数据库时添加一个网格。但是,当添加一个新值时,虽然它的键不同,但数据库仍然会用新的索引替换旧的索引。

总而言之,这是我想要的结构:

User.UID
|
|___ 0 -> cross
|
|___ 1 -> tick
|
|___ 2 -> cross
|
|___ 3 -> tick

但我得到了:

User.UID
|
|___ 1 -> tick

即:旧索引 0 被新索引 1 替换。

我的代码是:

playGame(int index, final databaseReference) {
    if (this.gameState[index] == "empty") {
      setState(() {
        if (this.isCross) {
          this.gameState[index] = "cross";
        } else {
          this.gameState[index] = "circle";
        }
        this.isCross = !this.isCross;
        this.checkWin();
      });

      databaseReference
          .child(authUser.currentUser.uid)
          .set({index.toString(): gameState[index]});
    }

网格:

Container(
                margin: EdgeInsets.all(15),
                height: MediaQuery.of(context).size.height / 2,
                color: Colors.white12,
                child: GridView.builder(
                  padding: EdgeInsets.only(top: 30),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      childAspectRatio: 1.0,
                      crossAxisSpacing: 10.0,
                      mainAxisSpacing: 10.0),
                  itemCount: 9,
                  itemBuilder: (context, i) => SizedBox(
                    child: MaterialButton(
                      onPressed: () {
                        this.playGame(i, databaseReference);
                      },
                      child: Image(
                        image: this.getImage(this.gameState[i]),
                      ),
                    ),
                  ),
                ),
              ),

谁能帮我解决这个问题?

【问题讨论】:

  • playGame(int index 怎么叫?
  • 抱歉回复晚了。每当用户单击网格时都会调用 playGame()。请查看我为网格添加的代码,其中调用了 playGame()。谢谢!
  • 谢谢。不过,您必须自己进行一些调试,因为 Stack Overflow 是一个非常低效的交互式调试器。例如:当您在playGameprint(index) 时,它是否具有您期望的值?如果是这样,如果您在对set() 的调用上设置断点,它是否显示indexgameState[index] 的正确值?
  • 我想我无法正确描述我的问题。问题是由于某种原因,firebase 正在用新值覆盖旧值(即使它们的键不同)。尽管如此,我还是检查了索引值,它们符合预期。传递给 playGame() 的索引与传递给 set 函数的索引相同。想一想,我运气不好? :(

标签: firebase flutter firebase-realtime-database


【解决方案1】:

当您在某个位置调用 set(...) 时,它设置您传递到该位置的值,并覆盖该位置的任何现有值。

如果您只想更新位置中的特定键,请使用update(...) 方法。所以在你的情况下就是我:

databaseReference
  .child(authUser.currentUser.uid)
  .update({index.toString(): gameState[index]});

【讨论】:

  • 非常感谢你。这成功了。当它们更新时,我只需要在其他设备上获取这些属性。你能指出我的来源吗?不幸的是,在 firebase.google.com 上找不到任何可以正常工作的东西:(
  • 有关实时数据库的 FlutterFire 文档和示例应用程序,请参阅 pub.dev/packages/firebase_database
猜你喜欢
  • 2021-04-25
  • 2020-07-12
  • 2021-12-24
  • 2020-09-13
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
相关资源
最近更新 更多