【问题标题】:Future returns correct data but snapshot shows null未来返回正确的数据,但快照显示为空
【发布时间】:2020-11-15 15:38:21
【问题描述】:

所以我正在尝试实现搜索功能,如您所见,我正在使用FutureBuilder 来执行此操作。当 API 调用它时,它按预期返回结果,但是当我尝试在 Future 构建器中使用它时,它的数据始终为空:

@override
  Widget buildResults(BuildContext context) {
    return FutureBuilder<List<SearchModel>>(
      future: getResults(),
      builder: ( BuildContext context, AsyncSnapshot<List<SearchModel>> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          logger.d(snapshot.hasData);
          return ListView.builder(
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(snapshot.data[index].title),
                onTap: () {
                  close(context, snapshot.data[index]);
                },
              );
            },
            itemCount: snapshot.data.length,
          );
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

Future<List<SearchModel>> getResults() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String language = prefs.getString('language');
    var data;
    List<SearchModel> results = [];

    data  = await http.get(Constants.BASE_URL + "/search/" + language + "/" + query,);
    results = (data.map((model) => SearchModel.fromJson(model)).toList());
    return results;
  }

【问题讨论】:

  • if (snapshot.connectionState == ConnectionState.done) { 之前添加print(snapshot) - 您在日志中看到了什么?
  • AsyncSnapshot>(ConnectionState.done, null, NoSuchMethodError: 类 'Response' 没有实例方法 'map'。接收者: 'Response' 的实例尝试调用: map(Closure: (动态)=> SearchModel))
  • 我收到与上述相同的错误:NoSuchMethodError: Class 'Response' has no instance method 'map'。接收方:“响应”实例尝试调用:map(Closure: (dynamic) => SearchModel)

标签: flutter future


【解决方案1】:

我不知道你的 API 和它的 JSON 响应,所以这是你的代码应该是什么样子的最佳猜测:

Future<List<SearchModel>> getResults() async {
    final prefs = await SharedPreferences.getInstance();
    final language = prefs.getString('language');

    final response = await http.get(Constants.BASE_URL + "/search/" + language + "/" + query);
    final results = ((response.body as List).map((model) => SearchModel.fromJson(model)).toList());

    return results;
}

也就是说,您需要检查FutureBuilder 是否有snapshot.hasError,并且您需要检查您对response.statusCode == 200 的回复(或任何适合该呼叫的内容),因为外部可能会出现很多问题打电话,你需要你的应用在这种情况下不会崩溃。

【讨论】:

    【解决方案2】:

    虽然 Future 尚未解析,但 snapshot.data 为 null,请检查 snapshot.connectionState == ConnectionState.done 或 snapshot.data != null 并在 else 中返回 Loading 小部件(带有 Loading 小部件/进度指示器或类似的)以及 if 中的功能部件。

    【讨论】:

    • 你应该真正阅读问题和代码,而不仅仅是根据标题回答。
    猜你喜欢
    • 1970-01-01
    • 2019-11-22
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多