【发布时间】: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 是一个非常低效的交互式调试器。例如:当您在
playGame中print(index)时,它是否具有您期望的值?如果是这样,如果您在对set()的调用上设置断点,它是否显示index和gameState[index]的正确值? -
我想我无法正确描述我的问题。问题是由于某种原因,firebase 正在用新值覆盖旧值(即使它们的键不同)。尽管如此,我还是检查了索引值,它们符合预期。传递给 playGame() 的索引与传递给 set 函数的索引相同。想一想,我运气不好? :(
标签: firebase flutter firebase-realtime-database