Get a single entry from firebase real time database from flutter project

Viewed 119

Im am trying to implement a CRUD operation in my flutter project with firebase real time database. I have a real time database in my project in Firebase. The structure firebase database structure looks like the image below.

Database structure

I can successfully write a single entry and read all entries from DeviceTokens. However, the problem im facing is while trying to read and display a single entry from the DeviceTokens.

I want to fetch any entry from the DeviceTokens according to their id and display the device_token and subscribed value of that id.

So far I have tried 2 approaches.

Approach 1:

final dbRef = FirebaseDatabase.instance.reference().child('DeviceTokens');

FutureBuilder(
          future: dbRef.once(),
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            if (snapshot.hasData) {
              Map<dynamic, dynamic> values = snapshot.data.value;
              values.forEach((key, value) {
                print('The values are $values');
              });
            }
          },
        ),

This returns all the entries as key value pair:

The values are {a136634e4045b9a9: {subscribed: 1, device_token: asdfadfgb ikfghoiwrutf08rhgk enf gh98edf7 gu0sdfjnv sdjfu 0sdg}, ssdf4r34terf: {subscribed: 1, device_token: sdfasdfasdfasdfasdf9q04urq3fo4tiq3wrng}, b66080b213607d48: {subscribed: 0, device_token: dmnjjUuuTHWZS5X87x6jwS:APA91bEszXYEVMf6u-IMGoi4RaFgESYzVVtSRX5zJ72OD21vUqLJi47QjshNjmCBngOHyv18EaZL40RKRSTFQWjAJdKFPIFA9rW_EhhLKwmz5KDWC-h2cdBGyXbIvl_r72uU-d7PFhLt}, d021bf47db5bb489: {subscribed: 1}}

Approach 2: The best case for me so far

FutureBuilder(
          future: dbRef
              .orderByChild('device_token')
              .equalTo(
                  'asdfadfgb ikfghoiwrutf08rhgk enf gh98edf7 gu0sdfjnv sdjfu 0sdg').once(),
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            if (snapshot.hasData) {
              Map<dynamic, dynamic> values = snapshot.data.value;
              values.forEach((key, value) {
                print('The values are $values');
              });
            }
          },
        ),

In this case it returns only the entry I am looking for however I cannot print out the device_token or subscribed data individually.

My Questions are

  1. How do I query an entry according to their ID (ex: a136634e4045b9a9) and not by device_token.
  2. After querying the data how do I display/print out only the device_token or subscribed, etc.
0 Answers
Related