【问题标题】:List view not displaying data from stream列表视图不显示来自流的数据
【发布时间】:2020-07-13 23:20:56
【问题描述】:

我有以下服务,它连接到 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&lt;List&lt;Report&gt;&gt;(context);

但是,我的列表视图是在报表填充数据之前构建的,即使返回数据,列表视图也不会显示。

我单步执行代码,getReports 方法被命中,我检查了 Firestore,那里有超过 50 条记录。

我已经根据这个原始问题的建议调整了这个列表视图:List view throws an error before stream has finished retrieving data 但是删除了找出问题的条件。

谁能提出问题所在?

【问题讨论】:

    标签: flutter flutter-provider flutter-listview


    【解决方案1】:

    在获取报告数据之前,首先检查报告是否不等于空。

    检查此代码

    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: reports != null ? 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])),
                );
              }):
              CircularProgressIndicator(),
          floatingActionButton: FloatingActionButton(
            child: Icon(Icons.add),
            onPressed: () {
              _db.addReport();
            },
          ),
        );
      }}```
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      相关资源
      最近更新 更多