我将 flutter 与包 firebase_database 一起使用。随着代码
final FirebaseDatabase _database = FirebaseDatabase.instance;
@override
void initState() {
super.initState();
_newsList = new List();
_newsQuery = _database
.reference()
.child('news')
.orderByChild('published')
.limitToFirst(10);
_newsQuery.onChildAdded.listen(_onEntryAdded);
}
_onEntryAdded(Event event) {
setState(() {
News n = News.fromSnapshot(event.snapshot);
_newsList.add(n);
});
}
Run Code Online (Sandbox Code Playgroud)
我得到了_newsList所有查询项目的完美列表。新闻类是
import 'package:firebase_database/firebase_database.dart';
class News {
String key;
String image;
String text;
String title;
String published;
News(this.image, this.text, this.published);
News.fromSnapshot(DataSnapshot snapshot) :
key = snapshot.key,
text = snapshot.value["text"],
title = snapshot.value["title"],
image = snapshot.value["image"],
published = snapshot.value["published"];
toJson() …Run Code Online (Sandbox Code Playgroud)