Kit Mateyawa
Kit Mateyawa

Reputation: 197

How can I get the auto generated key from Firebase in my Flutter project?

This is a continuation from this post: I'd like to add a like button to this flutter blog app

Currently I can print out the auto generated keys in Firebase realtime database using print(snap.key);

My problem is adding it to this onTap function _incrementCounter. Not sure what to do here. Of course if I replaced+ snap.key + with any of the firebase posts key then the function will work for that paticular post only:

void _incrementCounter() async {
    try {
      var ref = FirebaseDatabase.instance.reference().child('posts/'+ snap.key +'/counter');
      await ref.once().then((data) async => {
        await ref.set(data.value + 1),
      });
    } catch (e) {
      print(e.message);
    }
  }
}

enter image description here

Any help is much appreciated. Thank you all!

Upvotes: 0

Views: 1360

Answers (1)

Thomas
Thomas

Reputation: 2560

You can just pass the key to your function. Or am I misunderstanding something?

...
onTap: (){
     _incrementCounter(postsList[index].key);
}
...

void _incrementCounter(key) async {
    try {
      var ref = FirebaseDatabase.instance.reference().child('posts/'+ key +'/counter');
      await ref.once().then((data) async => {
        await ref.set(data.value + 1),
      });
    } catch (e) {
      print(e.message);
    }
  }
}

Upvotes: 1

Related Questions