因此,我正在尝试实现搜索功能,如您所见,我正在使用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;
}
答案 0 :(得分: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
(或任何适合该呼叫的内容),因为有很多在外部通话中可能会出错,并且您需要在这种情况下不要使应用崩溃。
答案 1 :(得分:-1)
虽然未解决Future快照。数据为null,请检查snapshot.connectionState == ConnectionState.done或snapshot.data!= null,然后在else中返回“正在加载”窗口小部件(带有“正在加载”窗口小部件/“进度”指示器或类似控件)并将功能部件放置在if中。