android - 异步功能后更改正文
问题描述
我有一个带有包含 2 个选项卡的选项卡视图的搜索屏幕。启动时,每个选项卡中都有一个空容器。当用户运行搜索时,我想根据结果为每个选项卡生成一个网格视图。
到目前为止,这是我的代码应用程序主体
Widget tvScreen = new Container();
Widget movieScreen = new Container();
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(text: "TV Shows"),
Tab(text: "Movies"),
]),
centerTitle: true,
title: Padding(
padding: const EdgeInsets.only(right: 17.0),
child: new TextField(
autofocus: true,
style: new TextStyle(
fontSize: 18.0,
),
controller: _searchField,
decoration: InputDecoration(
hintText: "Enter TV Show or Movie...."
),
),
),
actions: <Widget>[
IconButton(
splashColor: Colors.white,
icon: Icon(Icons.search),
onPressed: _runSearch,
),
],
// MD2: make the color the same as the background.
backgroundColor: backgroundColor,
// Remove box-shadow
elevation: 18.00,
),
body: TabBarView(
children: [
tvScreen,
movieScreen,
]),
),
),
);
这就是我从 API 获取数据的方式
Future<String> getResults() async{
List<ResultsModel> _searchResults = [];
if (_searchField.text.isEmpty != true){
String _searchParam = _searchField.text.replaceAll(r" ", "%20");
String _apiKeyMovie = "https://api.themoviedb.org/3/search/movie?"
"api_key=b52e4dea6f4284&language=en-US&"
"query=$_searchParam&include_adult=true";
var data = await http.get(_apiKeyMovie);
var jsonData = jsonDecode(data.body);
print("Show JSON");
print(jsonData);
if (jsonData != null) {
int totalResults = jsonData["results"].length;
if (totalResults != 0){
int counter = 0;
while (counter != totalResults) {
if (jsonData["results"][counter]["poster_path"] != null){
ResultsModel result = ResultsModel(
true, jsonData["results"][counter]["title"],
jsonData["results"][counter]["id"],
"http://image.tmdb.org/t/p/w185/${jsonData["results"][counter]["poster_path"]}");
_searchResults.add(result);
counter = counter + 1;
} else counter = counter + 1;
}
}
}
}
searchResults = _searchResults;
return "Done!";
按下按钮进行开关
_runSearch(){
getResults();
setState(() {
//Change tabview contents
tvScreen = _uiBodyTV();
movieScreen = _uiBodyMovie();
});
解决方案
您应该考虑使用 FutureBuilder 小部件。
推荐阅读
- node.js - 从 Marketplace 安装时,VSCode 扩展找不到模块
- javascript - 在Javascript中使用数组数据制作表格
- python - 即使您不提交任何内容,“MultipleFileField”也总是返回 True,为什么?
- scala - 映射表列类型转换应用取消应用
- rust - 当 try_next 还没有任何项目时,流会阻塞线程
- php - 我正在尝试在 mod_rewrite 中模拟 else
- javascript - 来自 json 文件的 Swagger 示例帖子正文引用
- excel - VB.Net Excel 临时文件性能问题
- python - Python - 为什么 import * in package 不起作用?
- jquery - 如何使用 jQuery 在数据库中以表格格式再次存储和检索 HTML 表格中的值?