Reputation: 21
I am trying to get a list of data from a firebase database and display it as a list in my flutter app, at the moment I cannot get the data to appear, on the UI.When I try and print the list it does not contain any values when it should show the names I have entered in the database.
This is the database that I am trying to retrieve:
This is the code that I have implemented for my UI, any ideas on what is the issue here?
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'SignInSuccessPage.dart';
class SignInPage extends StatefulWidget {
@override
SignInPageState createState() => SignInPageState();
}
class SignInPageState extends State<SignInPage> {
List<Volunteer> volunteers;
Volunteer volunteer;
DatabaseReference volunteerRef;
@override
void initState() {
super.initState();
volunteers = new List();
volunteer = Volunteer("","", "");
final FirebaseDatabase database = FirebaseDatabase.instance; /
volunteerRef = database.reference().child('volunteerapp-cec4f');
volunteerRef.onChildAdded.listen(_onEntryAdded);
volunteerRef.onChildChanged.listen(_onEntryChanged);
}
_onEntryAdded(Event event) {
setState(() {
volunteers.add(Volunteer.fromSnapshot(event.snapshot));
});
}
_onEntryChanged(Event event) {
var old = volunteers.singleWhere((entry) {
return entry.key == event.snapshot.key;
});
setState(() {
volunteers[volunteers.indexOf(old)] = Volunteer.fromSnapshot(event.snapshot);
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('List of Names'),
),
resizeToAvoidBottomPadding: false,
body: Column(
children: <Widget>[
Flexible(
child: FirebaseAnimatedList(
query: volunteerRef,
itemBuilder: (BuildContext context, DataSnapshot snapshot,
Animation<double> animation, int index) {
return new ListTile(
title: Text(volunteers[index].firstName),
subtitle: Text(volunteers[index].lastName),
);
},
),
),
],
),
);
}
}
//the volunteer class which contains all the info about each volunteer object and links to firebase
class Volunteer {
String key;
String firstName;
String lastName;
Volunteer(this.key, this.firstName, this.lastName);
Volunteer.fromSnapshot(DataSnapshot snapshot)
: key = snapshot.key,
firstName = snapshot.value["firstName"],
lastName = snapshot.value["lastName"];
toJson() {
return {
"key": key,
"firstName": firstName,
"lastName": lastName,
};
}
}
Upvotes: 1
Views: 3429
Reputation: 600071
You don't need to include the name of your project as a child
call, it's already in the base reference.
So:
volunteerRef = database.reference();
Upvotes: 1