Stridermn
Stridermn

Reputation: 123

How do I print a list from a Firebase Database query using Flutter?

I'm trying to print a list of attributes from my firebase database. The database is currently structured like this:

enter image description here

I would first like to print a list of show names to the console so I can see that it works and then add it to a ListView later. Any help is appreciated!

import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

// This is the model class
class Mod {
  final String name;
  final String nextEpisode;
  final String prevEpisode;

  Mod(this.name, this.nextEpisode, this.prevEpisode);

  Mod.fromJson(Map<String, dynamic> json)
    : name = json['name'],
      nextEpisode = json['nextEpisode'],
      prevEpisode = json['prevEpisode'];
}


// This is the screen class
class FTest2 extends StatefulWidget {
  @override
  _FTest2State createState() => _FTest2State();
}

class _FTest2State extends State<FTest2> {

  List<Mod> list = List();

  MakeCall() {
    final mainReference = FirebaseDatabase.instance.reference();
    mainReference.child('-M5Uol7Xldnc8wvNXnNg').once().then((DataSnapshot dataSnapshot){
      this.setState(() {
        for(var value in dataSnapshot.value){
          list.add(Mod.fromJson(value));
        }
      });
    });
    print(list);
  }

  void getData() {
    MakeCall();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('This is App Bar for the FB Test')),
        body: Column(
          children: <Widget>[
            RaisedButton(
              child: Text('Press for data'),
              onPressed: () {
                getData();
              },
            ),
          ],
        ));
  }
}

Upvotes: 0

Views: 3113

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599011

You're looping over the nodes of one specific show, which means that your value is actually one of the child properties under that: name, nextEpisode, prevEpisode. What you're probably looking for is to listen to onChildAdded for all shows, and then get the name property for each:

mainReference.child('shows')
  .onChildAdded
  .forEach((event) => {
    print(event.snapshot.key+": "+event.snapshot.value.toString());
    this.setState(() {
      list.add(Mod.fromJson(event.snapshot.value["name"]));
    });
  });

Also see my answer form a few weeks ago here: Flutter: Firebase Real-Time database orderByChild has no impact on query result

Upvotes: 2

Peter Haddad
Peter Haddad

Reputation: 80914

Your reference is wrong, you need to traverse the database from top to the node you want to retrieve, therefore use the following:

final mainReference = FirebaseDatabase.instance.reference("shows");
mainReference.child('-M5Uol7Xldnc8wvNXnNg').once().then((DataSnapshot dataSnapshot){

pass the argument shows to the reference() method.

Upvotes: 1

Related Questions