Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

firebase - Flutter: Realtime database, append data under specific UID

I'm trying to add a grid on every click to real-time database. However, when a new value is added, although its key is different, still database replaces the old index with new one.

To summarise, this is my intended structure:

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

But I'm getting:

User.UID
|
|___ 1 -> tick

i.e: Old index 0 is replaced with new index 1.

My code is:

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]});
    }

Grid:

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]),
                      ),
                    ),
                  ),
                ),
              ),

Can anyone please help how can I fix this?

question from:https://stackoverflow.com/questions/65864436/flutter-realtime-database-append-data-under-specific-uid

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you call set(...) on a location, it sets the values you pass to that location, overwriting any existing value(s) at the location.

If you want to only update specific keys in the location, use the update(...) method. So in your case that'd me:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...