我正在尝试使用模型从Firebase实时数据库中将数据检索到Flutter中的列表中。执行此操作时,我的列表将返回null。我还阅读了其他有关在Flutter上使用Firebase的文章,但没有找到明确的答案。这是我目前的方法(该对象称为“需求”,我正在尝试检索并显示需求列表):
型号:
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;
}
}
ListView:
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实时数据库结构:
我在做什么错了?
答案 0 :(得分:1)
Map<dynamic, dynamic> values = needsSnapshot.data.value;
是错误的。
值就是数据,所以只需使用Map<dynamic, dynamic> values = needsSnapshot.value;
您添加到列表的对象也不会转换。
// wrong
Map<dynamic, dynamic> values = needsSnapshot.data.value;
values.forEach((key, values) {
needs.add(values);
});
// correct
Map<dynamic, dynamic> values = needsSnapshot.data.value;
values.forEach((key, values) {
needs.add(Need.fromSnapshot(values));
});
还有一件事,我对此不是100%肯定,但是如果我将List声明为null,则在向其添加值时会遇到问题,因此我始终将as声明为空列表。
因此,我会使用List<Need> needs;
List<Need> needs = [];
希望您已经解决了这个问题,但是如果没有解决的话。我只是遇到了同样的问题。 干杯
答案 1 :(得分:1)
尝试一下
needsSnapshot.once().then((DataSnapshot snapshot){
print(snapshot.value.entries.length);
for (var val in snapshot.value.entries){
needs.add(new Need(val.id, val.imageUrl,val.caption,val.title));
//print(val.value.toString());
}
//print(needs.length);
答案 2 :(得分:0)
创建一个模型来容纳对象。在其中创建一个方法,如下所示,
ModelName.fromJson(Map<String, dynamic> json) {
property1 = json['property1'];
property2 = json['property2'];
}
使用以下方法直接将 Firebase 数据快照转换为模型。
databaseRef.once().then((DataSnapshot snapshot) {
for(var data in snapshot.value)
{
var model = Model.fromJson(Map<String, dynamic>.from(data));
logger.i(model.iponame);
}
});
答案 3 :(得分:-1)
请注意,如果上述方法可行,则可以实现以下目标:
List<Need> yourNeeds=[];
await firestore.collection("Need")
.getDocuments()
.then((QuerySnapshot snapshot) {
snapshot.documents.forEach((f) {
Needs obj= new Need();
obj.field1=f.data['field1'].toString();
obj.field2=f.data['field2'].toDouble();
//Adding value to your Need list
yourNeeds.add(obj);
});