【发布时间】: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)