导入http :
http: ^0.12.2
Future异步get方式:
postTest().then((value) => {
setState(() {
print("请求结果:${value.toString()}");
runPost();
})
});
postTest() async {
var uri = Uri.parse(
'http://www.devio.org/io/flutter_app/json/test_common_model.json');
//get
var response = await http.get(uri);
print('Response status: ${response.statusCode}');
print('Response body: ${Utf8Decoder().convert(response.bodyBytes)}');
return Utf8Decoder().convert(response.bodyBytes));
}
FutureBuilder 异步携带请求进度状态 Post方式:
//异步处理 ,携带状态,更符合实际生产
FutureBuilder<String>(
future: test(),
builder: (context, shot) {
switch (shot.connectionState) {
case ConnectionState.active:
return Text("active....");
case ConnectionState.waiting:
return Center(
child: CircularProgressIndicator(),
);
case ConnectionState.done:
var text = Text("");
if (shot.hasError)
text = Text("error:${shot.error.toString()}");
else
text = Text("done:${shot.data.toString()}");
return text;
case ConnectionState.none:
return Text("none....");
}
})
Future<String> test() async {
var url = Uri.parse('https://example.com/whatsit/create');
var response =
await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print('Response status: ${response.statusCode}');
print('Response body: ${Utf8Decoder().convert(response.bodyBytes)}');
return Utf8Decoder().convert(response.bodyBytes);
}