Polly
Polly

Reputation: 47

Get field and values from firebase flutter

How will i be able to retrieve the field and field values from firebase?

i want to retrieve "total payment" and its value and store it in array. Below is my code for getting the field values but not the field names.

Future _getDataFromDatabase() async {
    await FirebaseFirestore.instance.collection("payments").doc(FirebaseAuth.instance.currentUser!.uid).get().then((snapshot)async{
      if(snapshot.exists){
        setState((){
          totalPayments = snapshot.data()!["total payment"].toString();
          balance = snapshot.data()!["remaining balance"].toString();
          print(totalPayments);     
        });
      }
    });
  }

enter image description here

Upvotes: 1

Views: 41

Answers (1)

Joe
Joe

Reputation: 2243

snapshot is of type Map<String, dynamic> so if I understand your question correctly you are asking how to cast a map into a list with its keys preserved as string values.

you can get a list of a key-value pairs using something like

IterableZip([snapshot.keys, snapshot.values])

and then you can flatten it into a list using any approach but the shortest would be using expand so the final code would be:

import 'package:collection/collection.dart';
//... after that you can use
IterableZip([snapshot.keys, snapshot.values]).expand((i) => i).toList()

Upvotes: 2

Related Questions