在flutter应用程序中,我实现了简单的搜索视图,用户可以从Web服务器中搜索单词,可以使用我的http
方法进行呼叫并获取数据,并且可以在console
上打印结果,但是我可以t将其显示在listview
中。
可能的布局:
Container(
height: 70.0,
child: Row(
children: <Widget>[
Flexible(
flex: 1,
child: Padding(
padding: const EdgeInsets.only(left: 8.0),
child: TextField(
controller: _searchController,
textAlign: TextAlign.start,
keyboardType: TextInputType.text),
textInputAction: TextInputAction.send,),
),
),
InkWell(
child: Container(
height: 40.0,
width: 40.0,
child: Icon(Icons.send, size: 25.0, color: Colors.black),
),
onTap:_search,
),
],
),
),
Expanded(
child: FutureBuilder(
future: _searchPost(),
builder: (context, snapshot) {
if(snapshot.hasData) {
List<Contents> content = snapshot.data;
ListView.separated(
itemBuilder: (context, index) {
return ListTile(
title: Text(content[index].title),
),
subtitle: Text(content[index].createdAt),
),
);
},
itemCount: content.length,
separatorBuilder: (context, index) {
return Divider(height: 1.0);
},
);
}else if (snapshot.hasError){
print('error);
}
return Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.blue),
),
);
}),
)
http调用方法:
Future<List<Contents>> _searchPost() async {
final response = await http.get('${Constants.searchPosts}${_searchController.text}').timeout(Duration(seconds: 1));
if(response.statusCode == 200){
final responseString = json.decode(response.body) as List;
List<Contents> res= responseString.map((j)=>Contents.fromJson(j)).toList();
print(json.decode(response.body));//<-- work fine and show result in console
return res;
}else{
return null;
}
}
并单击离子按钮进行搜索:
void _search() {
if (_searchController.text.length <= 0) {
}else{
_searchPost();
}
}
答案 0 :(得分:0)
您在第一个if中缺少return
语句
if(snapshot.hasData) {
List<Contents> content = snapshot.data;
return ListView.separated(
itemBuilder: (context, index) {
return ListTile(
title: Text(content[index].title),
),
subtitle: Text(content[index].createdAt),
),
);
},
itemCount: content.length,
separatorBuilder: (context, index) {
return Divider(height: 1.0);
},
);
}else if (snapshot.hasError){
print('error);
return Container();
} else {
return Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.blue),
),
);
}