Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


1 Answers

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]});
like image 91
Frank van Puffelen Avatar answered Aug 10 '26 22:08

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!