Search code examples
flutterdartflutter-futurebuilder

Fetching data properly with Futurebuilder and json response


How can I render my response in my text widget?

My json snapshot.data is as following:

"{\"0\":{\"Breed\":\"American Hairless Terrier\",\"count\":1},\"1\":{\"Breed\":\"Bolognese\",\"count\":2},\"2\":{\"Breed\":\"Cavalier King Charles Spaniel\",\"count\":12},\"3\":{\"Breed\":\"Central Asian Shepherd Dog\",\"count\":1},\"4\":{\"Breed\":\"Papillon\",\"count\":1}}"

I tried to display my data like this:

Text(snapshot.data[index.toString()]['Breed']),

but I am getting:

type 'String' is not a subtype of type 'int' of 'index'

Solution

  • try this, might not be perfect but i will give you some idea, the error is because you are assigning int value to Text widget

    Text((snapshot.data[index]. 
      ['Breed']).toString());
     
         
     if you want to show it in 
      futureBuilder and listview 
       here:
    
        FutureBuilder(
           future: FirebaseFirestore. 
            instance.
           collection("groups").
           doc(groupId).snapshots(),
          //here your collection name 
           // and doc id
           builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
    if (!snapshot.hasData) {
      return Text("Loading");
    }
    var userDocument = snapshot.data["Breeds"];
    return ListView.builder(
    itemCount: userDocument.length,
      shrinkWrap: true,
      itemBuilder: (context, index) {
        return Text(userDocument[index]);
             ),
      }
    

    );