颤振如何从异步功能获取数据

时间:2019-11-06 00:27:04

标签: asynchronous flutter android-sqlite

我在处理这个问题时非常困难。我调用了一个异步函数,该函数将从SQLite获取一些信息,但我似乎无法获取。它只是呈现一个空白屏幕,在其中应该是列表视图。

List allItems = new List();


Future<void> pegaDados() async{
  var itens = await geraCardapio();

  for (var i = 0; i < itens.length; i++) {
    print((itens[i].toMap()));
    allItems.add(itens[i].toMap());
  }

}

print(pegaDados());


  return ListView.builder(
    itemCount: allItems.length,
    itemBuilder: (context, index) {
      return ListTile(
        leading: Image.asset("assets/"+ allItems[index]['imagem'], fit: BoxFit.contain,),
        title: Text(allItems[index]['pedido']),
        trailing: Text(allItems[index]['valor']),
      );
    },
  );

非常感谢您。

由于两个人都回答了这个问题,我设法得到了解决方案(使用这两种方法我都得到了这个小科学怪人)

    Future<dynamic> pegaDados() async{
  var allItems = await geraCardapio();

  return allItems.map((allItems) => allItems.toMap());
}



return FutureBuilder(
      future: pegaDados(),
      builder: (context, snapshot){
        if(snapshot.connectionState == ConnectionState.done){
          print(snapshot.data);
          var objeto = [];

          for (var i in snapshot.data) {
            objeto.add(i);
          }

          print(objeto);
          return Container(
              child: ListView.builder(
            itemCount: objeto.length,
            itemBuilder: (context, index) {
              return ListTile(
                leading: Image.asset("assets/"+ objeto[index]['imagem'], fit: BoxFit.contain,),
                title: Text(objeto[index]['pedido']),
                trailing: Text(objeto[index]['valor'].toString()),
              );
            },
              ),
          );
        }
        else if(snapshot.hasError){
          throw snapshot.error;
        }
        else{
          return Center(child: CircularProgressIndicator());
        }
      },
    );

感谢Mohammad Assem NasserEliya Cohen的帮助!

2 个答案:

答案 0 :(得分:2)

我不确定您的小部件树是什么样子,但是我假设ListViewpegaDados同时构建。您正在寻找的是FutureBuilder


Future<dynamic> pegaDados() async{
  var items = await geraCardapio();

  return items.map((item) => item.toMap());
}

...
FutureBuilder<dynamic>(
  future: pegaDados(),
  builder: (BuilderContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        return Text('Uninitialized');
      case ConnectionState.active:
      case ConnectionState.waiting:
        return Text('Awaiting result...');
      case ConnectionState.done:

        if (snapshot.hasError)
          throw snapshot.error;

        //
        // Place here your ListView.
        //
    }
    return null; // unreachable
  }

答案 1 :(得分:2)

您应该首先了解什么是Future操作(在您的情况下为Future函数)。以后的操作是需要时间才能执行并稍后返回结果的操作。为了解决此问题,我们使用异步函数

异步功能可让您的程序在执行当前操作时继续执行其他操作。 Dart使用Future对象(期货)来表示异步操作的结果。要处理这些操作,我们可以使用 async / await ,但是无法在小部件上集成async和await。因此,处理小部件中的期货非常棘手。为了解决这一问题,Flutter提供了一个名为FutureBuilder的小部件。

FutureBuilder中,它调用 Future函数以等待结果,并在生成结果后立即调用 builder函数。构建小部件。

这是应该的样子:

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  List allItems = new List();

  Future<List> pegaDados() async{
    var items = await geraCardapio(); // TODO: Add this function to this class

    for (var i = 0; i < items.length; i++) {
      print((items[i].toMap()));
      allItems.add(items[i].toMap());
    }
  return items;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: Text('Demo')),
      body: FutureBuilder(
        future: pegaDados(),
        builder: (context, snapshot){
          if(snapshot.connectionState == ConnectionState.done){
            return Container(
                child: ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, index) {
                return ListTile(
                  leading: Image.asset("assets/"+ snapshot.data[index]['imagem'], fit: BoxFit.contain,),
                  title: Text(snapshot.data[index]['pedido']),
                  trailing: Text(snapshot.data[index]['valor']),
                );
              },
                ),
            );
          }
          else if(snapshot.hasError){
            throw snapshot.error;
          }
          else{
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

此处是一段简短视频的link,它将以简洁的方式解释FutureBuilder