0

我一直在学习Flutter并关注关于包的在线教程Provider,目前我正在使用StreamProvider.

我有一个服务,它连接Firestore并返回集合中的所有文档(“报告”),然后将这些文档映射到我的报告对象。

服务:

class FirestoreService {
Firestore _db = Firestore.instance;
var random = Random();

Stream<List<Report>> getReports() {
return _db.collection('reports')
      .orderBy('timeStamp', descending: true)
      .snapshots()
      .map((snapshot) => snapshot.documents
      .map((document) => Report.fromJson(document.data))
      .toList());
}

报告类:

class Report {
final int temp;
final String wax;
final String line;
final String timeStamp;

Report({this.line,this.temp,this.timeStamp,this.wax});

Report.fromJson(Map<String, dynamic> parsedJson)
 : temp = parsedJson['temp'],
   wax = parsedJson['wax'],
   line = parsedJson['line'],
   timeStamp = parsedJson['timeStamp'];

}

main.dart我使用MultiProvider并添加了我的StreamProvider.

主要飞镖:

void main() => runApp(MyApp());

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.dart我检索报告数据并构建列表视图中,但是在getReports方法完成之前调用列表视图,并且在引用时偶尔会抛出错误var reports

home.dart:

class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
var reports = Provider.of<List<Report>>(context);
FirestoreService _db = FirestoreService();

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: Text(report.temp.toString()),
            title: Text(report.wax),
            subtitle: Text(report.line),
            trailing: Text(formatDate(DateTime.parse(report.timeStamp), [h, ':', mm, ' ', am])));
      }
      ) ,
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          _db.addReport();
        },
      ),
);
}}

例如,这一行特别抛出了一个错误:

itemCount: reports.length

此时报告为空,所以我的问题是如何防止在 getReports 方法完成之前构建列表视图?处理此类任务的最佳方法是什么?

谢谢

4

1 回答 1

0

尝试这个:

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var reports = Provider.of<List<Report>>(context);
    FirestoreService _db = FirestoreService();

    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: reports!=null ? (reports.length > 0 ? ListView.builder(
          itemCount: reports.length,
          itemBuilder: (context, index) {
            Report report = reports[index];
            return ListTile(
                leading: Text(report.temp.toString()),
                title: Text(report.wax),
                subtitle: Text(report.line),
                trailing: Text(formatDate(DateTime.parse(report.timeStamp), [h, ':', mm, ' ', am])));
          }
      ): Center(child: Text("We have received no data")))   : Center(child: Text("We are fetching data.Please wait...")),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          _db.addReport();
        },
      ),
    );
  }}
于 2020-04-01T23:16:43.823 回答