我正在开发一个flutter应用程序,其中Build方法调用fetchCitiesList方法用于城市列表,它将cities变量设置为cities.And Build方法用它来制作listtile列表。
var cities;
void fetchCitiesList () async {
var url = 'https://gnsyms.000webhostapp.com/cities.php';
var json;
var httpClient = new HttpClient();
try {
var req = await httpClient.getUrl(Uri.parse(url));
var res = await req.close();
if (res.statusCode == HttpStatus.OK) {
json = await res.transform(UTF8.decoder).join();
cities = JSON.decode(json);
}
} catch (exception) {
print(exception);
}
}
@override
Widget build(BuildContext context) {
final double systemTopPadding = MediaQuery.of(context).padding.top;
fetchCitiesList();
return new Scaffold(
appBar: new AppBar(
title: new Center( child: new Text(widget.title,textScaleFactor: 1.3,), ),
),
body: new Center(
child: new Column(
children: <Widget>[
new Padding(padding: new EdgeInsets.fromLTRB(0.0, 228.0, 0.0, 15.0) , child: new Text('Select A City',style:_biggerFont)),
new DropdownButton(
items: new List.generate(cities.length, (int index){
return new DropdownMenuItem(child: new Container(
child: new Center(
child:new Text(cities[index],textScaleFactor: 1.4,))
,width: 250.0,),value: cities[index],);
}),
value: city,
onChanged: (arg){
setState((){
city = arg;
print(arg);
});
}),
new Padding(padding: new EdgeInsets.fromLTRB(0.0, 15.0, 15.0, 0.0),
child : new IconButton(icon: new Icon(Icons.arrow_forward,color: Colors.blue,size: 60.0,),
onPressed: _produceHospitalCards)),
],
),
)
);
}
但它导致以下异常。所以,如何停止执行,直到异步函数完成它的任务。
The following NoSuchMethodError was thrown building MyHomePage(dirty, state:
I/flutter ( 7695): _MyHomePageState#ec54c):
I/flutter ( 7695): The getter 'length' was called on null.
I/flutter ( 7695): Receiver: null
I/flutter ( 7695): Tried calling: length
答案 0 :(得分:3)
您应该使用FutureBuilder
小部件。
以下是docs:
new FutureBuilder<String>(
future: _calculation, // a Future<String> or null
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none: return new Text('Press button to start');
case ConnectionState.waiting: return new Text('Awaiting result...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return new Text('Result: ${snapshot.data}');
}
},
)
关于您的情况:如果您让fetchCitiesList()
返回城市列表,则可以从示例中调用fetchCitiesList()
而不是_calculation
,然后通过执行{{{}来获取数据1}}。
希望这会有所帮助。