How to iterate through Flutter AsyncSnapshot<DataSnapshot> for FirebaseAnimated List?

2,666

Solution 1

I'm not sure I understand your question, I don't think you need a FutureBuilder here. The FirebaseAnimatedList already gives you the data in the followerSnap argument of the itemBuilder.

P.S. Generally you should prefer StreamBuilder with onValue instead of FutureBuilder and once(), so your data won't get stale.

Solution 2

I think you are more asking here about how to iterate over your JSON object which is not related to the title of the question, if this what you are asking for, you should still follow Collin's advice.

You stated that the data value looks like this

{aZb6KxxIuWA: {Value: 1, vidImage: https://i.ytimg.com/vi/aZb6KxxIuWA/mqdefault.jpg, vidId: aZb6KxxIuWA, vidTitle: 10 Embarrassing K-POP Star Fails And Accidents}, 4408NthSJis: {Value: 1, vidImage: https://i.ytimg.com/vi/4408NthSJis/mqdefault.jpg, vidId: 4408NthSJis, vidTitle: [TOP 100] MOST VIEWED K-POP MUSIC VIDEOS • APRIL 2017}, 7n5ieHnu90w: {Value: 1, vidImage: https://i.ytimg.com/vi/7n5ieHnu90w/mqdefault.jpg, vidId: 7n5ieHnu90w, vidTitle: BTS - I NEED U {Color coded lyrics Han|Rom|Eng}}, 8kyG5tTZ1iE: {Value: 1, vidImage: https://i.ytimg.com/vi/8kyG5tTZ1iE/mqdefault.jpg, vidId: 8kyG5tTZ1iE, vidTitle: SHINee 샤이니_Sherlock•셜록 (Clue + Note)_Music Video}, iy94tB5MldE: {Value: 1, vidImage: https://i.ytimg.com/vi/iy94tB5MldE/mqdefault.jpg, vidId: iy94tB5MldE, vidTitle: Simon D (사이먼디) - 짠해 (Cheerz) [MV ENG SUB]}, XuSYtAsMxfY: {Value: 1, vidImage: https://i.ytimg.com/vi/XuSYtAsMxfY/mqdefault.jpg, vidId: XuSYtAsMxfY, vidTitle: YOUTUBERS REACT TO K-Pop #3}, IZ1t7CwfvEc: {Value: 1, vidImage: https://i.ytimg.com/vi/IZ1t7CwfvEc/mqdefault.jpg, vidId: IZ1t7CwfvEc, vidTitle: GOT7 "Never Ever" M/V}, 2ips2mM7Zqw: {Value: 2, vidImage: https://i.ytimg.com/vi/2ips2mM7Zqw/default.jpg, vidId: 2ips2mM7Zqw, vidTitle: BIGBANG - 뱅뱅뱅 (BANG BANG BANG) M/V}, IlJHZJ8EqeA: {Value: 2, vidImage: https://i.ytimg.com/vi/IlJHZJ8EqeA/mqdefault.jpg, vidId: IlJHZJ8EqeA, vidTitle: MINO - '몸(BODY)' M/V}, 0Pinupmqwaw: {Value: 5, vidImage: https://i.ytimg.com/vi/0Pinupmqwaw/default.jpg, vidId: 0Pinupmqwaw, vidTitle: 직 재스퍼 (Zick Jasper) - PRIMETIME (Feat. 지구인)}}

Just to show you how this works, replace your Text with a FlatButton, and call _handleJson method in the onPressed callback, _handleJson takes userSnap.data.value as a parameter, as follows:

   default:
if (userSnap.hasError)
    return new Text('Error: ${userSnap.error}');
else
    print(userSnap.data.value.toString());
    return new Container(
       new FlatButton(onPressed: _handleJson(userSnap.data.value),
          child: new Text("Load Data"),);

and your method looks like this

_handleJson(value) {
    List myList = new List();
    for (var value in value.values) {
      myList.add(value);
    }
    print(myList);
  }

This should work if you JSON is primarily encoded, let me know if this worked with you.

Share:
2,666
Charles Jr
Author by

Charles Jr

Jack of All Trades - Master of Few!! Started with Obj-C.then(Swift)!.now(Flutter/Dart)! Thank everyone for every answer, comment, edit, suggestion. Can't believe I've been able to answer a few myself :-)

Updated on December 03, 2022

Comments

  • Charles Jr
    Charles Jr over 1 year

    I'm trying to iterate through my Firebase tree in order to populate a FirebaseAnimatedList. I need to use the key along with all the provided values. I'm assuming since iteration is built into the widget asynchronously, that's the reason it's not working exactly like JSON iteration. Here is my code...

    child: new FirebaseAnimatedList(
                          query: fb.child('NumberOnes').orderByChild('Value'),
                          padding: new EdgeInsets.all(8.0),
                          reverse: false,
                          itemBuilder: (_, DataSnapshot followerSnap,
                              Animation<double> animation, int Index) {
                            return new FutureBuilder<DataSnapshot>(
                                future: fb
                                    .child('NumberOnes')
                                    .orderByChild('Value')
                                    .once(),
                                builder: (BuildContext context,
                                    AsyncSnapshot<DataSnapshot> userSnap) {
                                  switch (userSnap.connectionState) {
                                    case ConnectionState.none:
                                      return new Text('Loading...');
                                    case ConnectionState.waiting:
                                      return new Text('Awaiting result...');
                                    default:
                                      if (userSnap.hasError)
                                        return new Text('Error: ${userSnap.error}');
                                      else
                                        print(userSnap.data.value.toString());
                                        return new Container(
                                          child: new Text(
                                              userSnap.data.value.toString()),
                                        );
                                  }
                                });
                          })
    

    Here is the log for print(userSnap.data.value.toString());...

    {aZb6KxxIuWA: {Value: 1, vidImage: https://i.ytimg.com/vi/aZb6KxxIuWA/mqdefault.jpg, vidId: aZb6KxxIuWA, vidTitle: 10 Embarrassing K-POP Star Fails And Accidents}, 4408NthSJis: {Value: 1, vidImage: https://i.ytimg.com/vi/4408NthSJis/mqdefault.jpg, vidId: 4408NthSJis, vidTitle: [TOP 100] MOST VIEWED K-POP MUSIC VIDEOS • APRIL 2017}, 7n5ieHnu90w: {Value: 1, vidImage: https://i.ytimg.com/vi/7n5ieHnu90w/mqdefault.jpg, vidId: 7n5ieHnu90w, vidTitle: BTS - I NEED U {Color coded lyrics Han|Rom|Eng}}, 8kyG5tTZ1iE: {Value: 1, vidImage: https://i.ytimg.com/vi/8kyG5tTZ1iE/mqdefault.jpg, vidId: 8kyG5tTZ1iE, vidTitle: SHINee 샤이니_Sherlock•셜록 (Clue + Note)_Music Video}, iy94tB5MldE: {Value: 1, vidImage: https://i.ytimg.com/vi/iy94tB5MldE/mqdefault.jpg, vidId: iy94tB5MldE, vidTitle: Simon D (사이먼디) - 짠해 (Cheerz) [MV ENG SUB]}, XuSYtAsMxfY: {Value: 1, vidImage: https://i.ytimg.com/vi/XuSYtAsMxfY/mqdefault.jpg, vidId: XuSYtAsMxfY, vidTitle: YOUTUBERS REACT TO K-Pop #3}, IZ1t7CwfvEc: {Value: 1, vidImage: https://i.ytimg.com/vi/IZ1t7CwfvEc/mqdefault.jpg, vidId: IZ1t7CwfvEc, vidTitle: GOT7 "Never Ever" M/V}, 2ips2mM7Zqw: {Value: 2, vidImage: https://i.ytimg.com/vi/2ips2mM7Zqw/default.jpg, vidId: 2ips2mM7Zqw, vidTitle: BIGBANG - 뱅뱅뱅 (BANG BANG BANG) M/V}, IlJHZJ8EqeA: {Value: 2, vidImage: https://i.ytimg.com/vi/IlJHZJ8EqeA/mqdefault.jpg, vidId: IlJHZJ8EqeA, vidTitle: MINO - '몸(BODY)' M/V}, 0Pinupmqwaw: {Value: 5, vidImage: https://i.ytimg.com/vi/0Pinupmqwaw/default.jpg, vidId: 0Pinupmqwaw, vidTitle: 직 재스퍼 (Zick Jasper) - PRIMETIME (Feat. 지구인)}}
    

    Eventually the plan is to populate this info into Cards within the Container instead of text.

    I'm not getting an error, but here is a screenshot of the 'Container' and Text.. enter image description here

    • Shady Aziza
      Shady Aziza over 6 years
      What kind of error it gives you?
    • Charles Jr
      Charles Jr over 6 years
      @aziza I've added what comes out on the simulator. I'm not getting an error, I'm just having trouble posting individual elements to my card
    • Shady Aziza
      Shady Aziza over 6 years
      and the problem is ??
    • Shady Aziza
      Shady Aziza over 6 years
      Aha, I understand.
  • Charles Jr
    Charles Jr over 6 years
    Can I have the ConnectionState functions with StreamBuilder? If so, can you point me towards a nice example/tutorial?
  • Charles Jr
    Charles Jr over 6 years
    / @collinjackson , No this did not work. Streambuilder iterates by itself so I got this error _StreamBuilderBaseState<Event, AsyncSnapshot<Event>>#d406d): Class '_InternalLinkedHashMap' has no instance getter 'iterator'. I did manage to get it working with my initial query from the FirebaseAnimatedList, but every time I updated a value the entire UI reset. I think I need to get my event out of its Map where I saved values grouped by vidId as aZb6KxxIuWA: above.
  • Shady Aziza
    Shady Aziza over 6 years
    So did you manage to get the data you want?, you need to break down your widgets such that only the widgets that needs said data is wrapped within the future builder so that the rest of the UI does not stall for no reason.
  • Charles Jr
    Charles Jr over 6 years
    I got the StreamBuilder to work properly. 1 thing, every time 1 of the elements change the entire list resets. So for example each Card has a counter that I would like to see add and subtract without the screen changing. How can I do this?
  • Collin Jackson
    Collin Jackson over 6 years
    Please post a new question
  • Charles Jr
    Charles Jr over 6 years