Flutter:为啥我的构建器在 Web 服务调用后没有重新加载?
Posted
技术标签:
【中文标题】Flutter:为啥我的构建器在 Web 服务调用后没有重新加载?【英文标题】:Flutter : Why is my builder not getting reloaded after web service call?Flutter:为什么我的构建器在 Web 服务调用后没有重新加载? 【发布时间】:2020-09-27 13:36:16 【问题描述】:我已经编写了 Web 服务调用,并在 initState()
方法中被调用。如果没有可用数据,则调用 CircularProgressIndicator()。但是,即使 Web 服务调用结束,进度指示器也会继续旋转!
进行服务调用后,为什么我的构建器没有重新加载?
我是新来的颤振!我哪里出错了?
class _DashboardState extends State<Dashboard>
bool isLoading = false;
Future<List<OrganizationModel>> fetchOrganizationData() async
isLoading = true;
var response = await http.get(organizationAPI);
if (response.statusCode == 200)
final items = json.decode(response.body).cast<Map<String, dynamic>>();
orgModelList = items.map<OrganizationModel>((json)
return OrganizationModel.fromJson(json);
).toList();
isLoading = false;
return orgModelList;
else
isLoading = false;
throw Exception('Failed to load internet');
@override
void initState()
this.fetchOrganizationData();
super.initState();
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text("Dashboard"),
),
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xFF076A72), Color(0xFF64B672)])),
child: Column(
children: <Widget>[
Container(
color: Color(0xFF34A086),
height: 1,
),
isLoading ? loadProgressIndicator() : Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 40, right: 40),
child: ListView(children: <Widget>[])
---my code goes here---
【问题讨论】:
【参考方案1】:你必须调用 setState(() => isLoading = false;) 这样 Flutter 才能更新视图的状态,这样做会隐藏你的 CircularProgressIndicator。
【讨论】:
【参考方案2】:Exception('Failed to load internet'); <-
这不是一个好主意,因为您在没有 try catch 块的情况下调用 fetchOrganizationData()
最好尝试一下:
class _DashboardState extends State<Dashboard>
bool isLoading = false;
bool isFailure = false;
List<OrganizationModel> orgModelList; // this was missing
//since your not using the return value ( it's saved in the state directly ) you could not set the return type
fetchOrganizationData() async
isLoading = true;
isFailure = false;
var response = await http.get(organizationAPI);
if (response.statusCode == 200)
final items = json.decode(response.body).cast<Map<String, dynamic>>();
orgModelList = items.map<OrganizationModel>((json)
return OrganizationModel.fromJson(json);
).toList();
isFailure = false;
// the return is not required
else
isFailure = true;
isLoading = false;
setState(()); // by calling this after the whole state been set, you reduce some code lines
//setState is required to tell flutter to rebuild this widget
这样你就有一个 isFailure 标志来表明在获取时是否出现问题。
【讨论】:
以上是关于Flutter:为啥我的构建器在 Web 服务调用后没有重新加载?的主要内容,如果未能解决你的问题,请参考以下文章