我有以下服务,它连接到 Firestore 并返回所有文档。
class FirestoreService {
Firestore _db = Firestore.instance;
var random = Random();
Stream<List<Report>> getReports() {
var data = _db
.collection('reports')
.orderBy('timeStamp', descending: true)
.snapshots()
.map((snapshot) => snapshot.documents
.map((document) => Report.fromJson(document.data))
.toList());
return data;
}
我使用 StreamProvider 并在我的main.dart
:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final FirestoreService _db = FirestoreService();
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (BuildContext context) => SettingsProvider()),
StreamProvider(create: (BuildContext context) => _db.getReports(),)
],
child: MaterialApp(
title: 'Wax App',
theme: ThemeData(
primarySwatch: Colors.deepPurple,
accentColor: Colors.deepOrangeAccent),
home: Home(),
),
);
}}
我的Home()
小部件如下:
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
FirestoreService _db = FirestoreService();
SettingsProvider settings = Provider.of<SettingsProvider>(context);
var reports = Provider.of<List<Report>>(context);
return Scaffold(
appBar: AppBar(
title: Text('Wax App'),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(Icons.settings),
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => Settings()));
})
],
),
body: ListView.builder(
itemCount: reports.length,
itemBuilder: (context, index) {
Report report = reports[index];
return ListTile(
leading: (settings.units == 'Metric')
? Text(report.temp.toString()+ '\u00B0')
: Text((((report.temp) * (9/5)) + 32).round().toString() + '\u00B0'),
title: Text(report.wax),
subtitle: Text(report.line),
trailing: Text(formatDate(
DateTime.parse(report.timeStamp), [h, ':', nn, ' ', am])),
);
}),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
_db.addReport();
},
),
);
}}
如您所见,我通过这一行检索报告:
var reports = Provider.of<List<Report>>(context);
但是,我的列表视图是在报表填充数据之前构建的,即使返回数据,列表视图也不会显示。
我单步执行了代码并找到了getReports
方法,我检查了 Firestore,那里有超过 50 条记录。
我已经根据这个原始问题的建议调整了这个列表视图:列表视图在流完成检索数据之前抛出错误,但是删除了找出问题的条件。
谁能建议问题是什么?