如何在列表视图中显示异步函数的结果

时间:2018-10-20 20:17:14

标签: firebase asynchronous dart flutter google-cloud-firestore

我正在尝试建立一个列表视图,以显示与他们各自的用户有关的一些事件,但是列表是在方法完成之前构建的,然后导致一个空列表...

我尝试过,但是问题仍然存在:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:project/Methods.dart';
import 'package:project/Views/CadastroUsuario.dart';
import 'package:project/classes/eventos.dart';

class ListagemEventos extends StatefulWidget {
  @override
  ListagemEventosState createState() => new ListagemEventosState();
}

class ListagemEventosState extends State<ListagemEventos> {
  @override
  void initState() {
    super.initState();
  }

  Future<List<Event>> getEvents() async {
    CollectionReference eventsDoc = Firestore.instance.collection("events");
    return await eventsDoc.getDocuments().then((snapshot) { 
       List<Event> events = new List<Event>();
       snapshot.documents.forEach((doc) async {
          Event event = new Event();  
          String id;         

          event.description      = doc["description"];
          event.city             = doc["city"];
          event.state            = doc["state"];
          event.location         = doc["location"];
          event.date             = doc["date"];
          event.placesAvailable  = doc["placesAvailable"];
          event.totalPlaces      = doc["placesTotal"];

          id = doc["userId"];
          event.owner = new UserOwner();

          CollectionReference eventsDoc = Firestore.instance.collection("users");
          event.owner = await eventsDoc.document(id).get().then((doc) {
            UserOwner userOwner = new UserOwner();
            userOwner.userid = id;
            userOwner.name   = doc["name"];
            userOwner.phone  = doc["phone"];
            userOwner.email  = doc["email"];
            userOwner.city   = doc["city"];
            userOwner.state  = doc["state"];
            userOwner.photo  = doc["photo"];

            event.owner = userOwner;

            return userOwner;
          });

          events.add(event);
        });

        return events;
    });
  }

  Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
    List<Event> events = snapshot.data;

    return new ListView.builder(
      itemCount: events.length,
      itemBuilder: (BuildContext context, int index){
        return item(events[index]);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Eventos'), 
      ),
      body: new FutureBuilder(
        future: getEvents(),
        builder: (BuildContext context, AsyncSnapshot snapshot){
          switch (snapshot.connectionState) {
            case ConnectionState.waiting: return new Text("Loading...");
            default: 
              if(snapshot.hasError)
                return new Text("Erro: ${snapshot.error}");
              else
                return createListView(context, snapshot);
          }
        },
      ),
      floatingActionButton: new FloatingActionButton(
        tooltip: 'Novo',
        child: new Icon(Icons.add),
        onPressed: () async {
          Navigation navigation = new Navigation();
          navigation.navigaTo(context, CadastroUsuario());
          },
      ),
    );
  }

  Widget item(Event event) {
    return new Card(
      elevation: 4.0,
      child: new Column(
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Column(
                children: <Widget>[
                  new Text(event.owner.name.toString(),
                    style: TextStyle(fontSize: 20.0),
                    overflow: TextOverflow.ellipsis,),
                ],
              ),
              new Column(
                children: <Widget>[
                ],
              )
            ],
          ),
          new Container(
            color: Colors.blue,
            height: 150.0,
          ),
          new Row(
            children: <Widget>[
              new Row(
                children: <Widget>[
                  new Text(event.description.toString(), 
                    style: TextStyle(fontSize: 20.0),
                    overflow: TextOverflow.ellipsis,),
                ],
              ),
              new Row(
                children: <Widget>[
                  new Text(event.location.toString(), 
                    style: TextStyle(color: Colors.grey[350]),
                    overflow: TextOverflow.ellipsis,),
                ],
              ),
              new Row(
                children: <Widget>[
                  new Text(event.city.toString() +' - '+ event.state.toString(), 
                    style: TextStyle(color: Colors.grey[350]),
                    overflow: TextOverflow.ellipsis,),
                ],
              )
            ]
          )          
        ],
      )
    );
  }
}

我该如何解决?
有其他方法可以做到吗?

PS:如果您能给我一个例子,我将不胜感激

2 个答案:

答案 0 :(得分:1)

由于我的代码还具有其他依赖性,因此我无法运行您的代码,因此,我将在不进行测试的情况下尽力帮助您。

关于颤动要记住的一件事(这使我更容易理解),除非调用此方法,否则视图永远不会刷新。

this.setState(() {});

因此,当您100%确定数据已加载时,请调用该函数。那将重建您的视图并再次调用build函数,这将刷新您的视图。希望对您有帮助。

知道了这一点,您可以使代码更加容易。您可以简单地创建一个变量,其子视图为子视图。将该变量填充到异步函数中,然后再次调用setState。这将填充列表视图。

答案 1 :(得分:0)

最后我找到了办法... 我正在initState中初始化一个侦听器,当我的Firestore发生更改时,我使用setState来重建我的普通列表视图

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:project/Methods.dart';
import 'package:project/Views/CadastroUsuario.dart';
import 'package:project/classes/eventos.dart';

class ListagemEventos extends StatefulWidget {
  @override
  ListagemEventosState createState() => new ListagemEventosState();
}

class ListagemEventosState extends State<ListagemEventos> {
  List<Event> _events;

  @override
  void initState() {
    super.initState();
    _events = new List<Event>();
    Firestore.instance.collection("events").snapshots().listen((snapshot){
      getEvents(snapshot);
    });
  }

  void getEvents(QuerySnapshot eventsDoc) {
    List<Event> events = new List<Event>();

    eventsDoc.documents.forEach((doc) async {
      Event event = new Event();  
      String id;         

      event.description      = doc["description"];
      event.city             = doc["city"];
      event.state            = doc["state"];
      event.location         = doc["location"];
      event.date             = doc["date"];
      event.placesAvailable  = doc["placesAvailable"];
      event.totalPlaces      = doc["placesTotal"];

      id = doc["userId"];
      event.owner = new UserOwner();

      CollectionReference eventsDoc = Firestore.instance.collection("users");
      event.owner = await eventsDoc.document(id).get().then((doc) {
        UserOwner userOwner = new UserOwner();
        userOwner.userid = id;
        userOwner.name   = doc["name"];
        userOwner.phone  = doc["phone"];
        userOwner.email  = doc["email"];
        userOwner.city   = doc["city"];
        userOwner.state  = doc["state"];
        userOwner.photo  = doc["photo"];

        event.owner = userOwner;

        return userOwner;
      });

      events.add(event);
      setState(() {
        _events = events;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Eventos'), 
      ),
      body: 
      _events.length == 0
      ?
        new Center(child: new CircularProgressIndicator())
      :
        new ListView.builder(
          itemCount: _events.length,
          itemBuilder: (BuildContext context, int index){
            return item(_events[index]);
          }
        )
      ,floatingActionButton: new FloatingActionButton(
        tooltip: 'Novo',
        child: new Icon(Icons.add),
        onPressed: () async {
          Navigation navigation = new Navigation();
          navigation.navigaTo(context, CadastroUsuario());
          },
      ),
    );
  }

  Widget item(Event event) {
    return new Card(
      elevation: 4.0,
      child: new Column(
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Column(
                children: <Widget>[
                  new Text(event.owner.name.toString(),
                    style: TextStyle(fontSize: 20.0),
                    overflow: TextOverflow.ellipsis,),
                ],
              ),
              new Column(
                children: <Widget>[
                ],
              )
            ],
          ),
          new Container(
            color: Colors.blue,
            height: 150.0,
          ),
          new Row(
            children: <Widget>[
              new Row(
                children: <Widget>[
                  new Text(event.description.toString(), 
                    style: TextStyle(fontSize: 20.0),
                    overflow: TextOverflow.ellipsis,),
                ],
              ),
              new Row(
                children: <Widget>[
                  new Text(event.location.toString(), 
                    style: TextStyle(color: Colors.grey[350]),
                    overflow: TextOverflow.ellipsis,),
                ],
              ),
              new Row(
                children: <Widget>[
                  new Text(event.city.toString() +' - '+ event.state.toString(), 
                    style: TextStyle(color: Colors.grey[350]),
                    overflow: TextOverflow.ellipsis,),
                ],
              )
            ]
          )          
        ],
      )
    );
  }
  }