我已经编写了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'); <-
这不是一个好主意,因为您没有尝试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标志,该标志指示在获取时是否出了问题。