我已经编写了 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---
你必须调用setState((( => isLoading = false;(,这样Flutter就可以更新视图的状态,这样做会隐藏你的CircularProgressIndicator。
Exception('Failed to load internet'); <-
这不是一个好主意,因为您在没有尝试捕获块的情况下调用 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标志,说明获取时是否出现问题。