我正在尝试使用模型将 Firebase 实时数据库中的数据检索到 Flutter 中的列表中。当我这样做时,我的列表返回为空。我已经阅读了其他几篇有关将 Firebase 与 Flutter 结合使用的文章,但尚未找到明确的答案。这是我当前的方法(该对象称为“需求”,我正在尝试检索并显示需求列表):
Model:
import 'package:firebase_database/firebase_database.dart';
class Need {
final String id;
final String imageUrl;
final String caption;
final String title;
Need({
this.id,
this.imageUrl,
this.caption,
this.title,
});
Need.fromSnapshot(DataSnapshot snapshot) :
id = snapshot.key,
imageUrl = snapshot.value["imageUrl"],
caption = snapshot.value["caption"],
title = snapshot.value["postTitle"];
toJson() {
return {
"imageUrl": imageUrl,
"caption": caption,
"title": title,
};
}
}
带有 Firebase 查询的数据库服务:
import 'package:firebase_database/firebase_database.dart';
import 'package:Given_Flutter/models/need_model.dart';
class DatabaseService {
static Future<List<Need>> getNeeds() async {
Query needsSnapshot = await FirebaseDatabase.instance
.reference()
.child("needs-posts")
.orderByKey();
print(needsSnapshot); // to debug and see if data is returned
List<Need> needs;
Map<dynamic, dynamic> values = needsSnapshot.data.value;
values.forEach((key, values) {
needs.add(values);
});
return needs;
}
}
列表显示:
import 'package:flutter/material.dart';
import 'package:Given_Flutter/models/need_model.dart';
import 'package:Given_Flutter/services/database_service.dart';
import 'package:Given_Flutter/need_view.dart';
class Needs extends StatefulWidget {
static final String id = 'needs_screen';
@override
_NeedsState createState() => _NeedsState();
}
class _NeedsState extends State<Needs> {
List<Need> _needs = [];
@override
void initState() {
super.initState();
_setupNeeds();
}
_setupNeeds() async {
List<Need> needs = await DatabaseService.getNeeds();
setState(() {
_needs = needs;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: RefreshIndicator(
onRefresh: () => _setupNeeds(),
child: ListView.builder(
itemCount: _needs.length,
itemBuilder: (BuildContext context, int index) {
Need need = _needs[index];
return NeedView(
need: need,
);
}
)
)
);
}
}
Firebase 实时数据库结构:
Firebase 示例
我究竟做错了什么?