【问题标题】:Return list from Future function in flutterFlutter中Future函数的返回列表
【发布时间】:2020-08-01 19:18:19
【问题描述】:

所以我在这里有一个未来函数,获取一个 json 文件,对其进行解析并将其附加到一个列表中。我想将数据返回给我拥有的另一个类,这样当我在另一个类上调用函数时,我会从函数中获取返回值。我该怎么做?

这是我的函数 class1.dart

Future search(String stock) async {
    print("Starting get request");
    data.clear();
    http.get("https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords=" + stock + "&apikey=demo").then((res){
      print("received response.");
      final search = searchFromJson(res.body);
      for(int i = 0; i < search.bestMatches.length; i++)
      {
          data.add(search.bestMatches[i].the1Symbol);
          data.add(search.bestMatches[i].the2Name);
      }
    }).catchError((e) {
      print("Failed to get response. " + e.toString());
    });
    return data;
  }

这是我在另一个类 class2.dart 上的另一个函数

  void  _infoModal(context, val) async{
    List<String> data = await _vantage.search(val);
    showModalBottomSheet(context: context, builder: (BuildContext bc) {
      return Container(
        child: Text(data[0]),
      );
    });
  }

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    要从其他类调用函数/方法,您应该具有该类对象的引用,或者您创建一个新对象,例如:

    Vantage _vantage = new Vantage();
    

    但第一个选项的问题是,如果你使用Navigator.pushReplacement,则无法调用,这意味着你的页面不在小部件树上。

    我个人建议你创建一个帮助类而不是传递类对象。

    【讨论】:

    • 我确实在二等舱顶部的某个地方有这个,但它仍然不起作用
    • 您是创建了辅助类还是只是创建了对 class1 的引用?
    • 还在搜索方法中声明“data”变量
    • 我没有辅助类。我认为它确实通过了,但模式在 API 返回值之前出现。我该如何解决这个问题?
    • 使用 FutureBuilder
    猜你喜欢
    • 2019-07-31
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多