Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter firebase database iterate over items

I'd like to know how to get a list of objects from a path on Flutter, here's how i get one object and works fine:

static Future<Year> getYear(
  String yearKey) async {
Completer<Year> completer = new Completer<Year>();

FirebaseDatabase.instance
    .reference()
    .child("year")
    .child(yearKey)
    .once()
    .then((DataSnapshot snapshot) {

  var year = new Year.fromJson(snapshot.key, snapshot.value);

  completer.complete(year);
});

return completer.future;
}

Now i am trying do this way to get a list of all years in the same path, but not know how iterage over items:

static Future<List<Year>> getYears() async {
    Completer<List<Year>> completer = new Completer<List<Year>>();

    List<Year> years = new List<Year>();

    FirebaseDatabase.instance
        .reference()
        .child("year")
        .once()
        .then((DataSnapshot snapshot) {

        //how to iterate over the items here?

      completer.complete(years);
    });

    return completer.future;
  }

Someone helps me please.

like image 513
Jorge Vieira Avatar asked Jun 01 '18 23:06

Jorge Vieira


1 Answers

I got this working, for someone that have the same problem:

static Future<List<Year>> getYears() async {
    Completer<List<Year>> completer = new Completer<List<Year>>();

    List<Year> years = new List<Year>();

    FirebaseDatabase.instance
        .reference()
        .child("year")
        .once()
        .then((DataSnapshot snapshot) {
          //here i iterate and create the list of objects
          Map<dynamic, dynamic> yearMap = snapshot.value;
          yearMap.forEach((key, value) {
            years.add(Year.fromJson(key, value));
          });

      completer.complete(years);
    });

    return completer.future;
  }

Here is the Year code:

class Year{
  String key;
  String name;

  Year({this.name});

  Year.fromJson(this.key, Map data){
    name = data['name'];
    if(name == null){
      name = '';
    }
  }
}

Thank you everyone.

like image 87
Jorge Vieira Avatar answered Nov 08 '22 13:11

Jorge Vieira