参考资料:https://blog.csdn.net/duo_shine/article/details/81280614
flutter http网络请求,可以使用已有的插件来完成。
插件版本: http: ^0.11.3+16
插件引入:
pubspec.yaml
dependencies:
flutter:
sdk: flutter
http: ^0.11.3+16
http工具类:
import 'package:http/http.dart' as http;
class HttpManager {
// 三天预报
var forecast_url = "https://free-api.heweather.com/s6/weather/forecast?parameters";
//实况天气
var new_weather_url = "https://free-api.heweather.com/s6/weather/now?parameters";
/**
* 三天预报
* cityName 城市名称 我们应该使用外部传入
* net 监听网络请求的结果 因为他不是同步的
*/
getForecast(NetListener net, String cityName) {
var client = new http.Client();
client.post(
forecast_url,
body: {
'location': cityName,
'key': 'eaf572c8304f4eeb8ad209bf05da2872'
}
).then((response){
net.onForecastResponse(response.body);
},onError: (error){
net.onError(error);
}).whenComplete(
client.close
);
}
/**
* 获取实况天气
*/
getNewWeather(NetListener net,String cityName) {
var client = new http.Client();
client.post(
new_weather_url,
body: {
"location": cityName,
"key": "eaf572c8304f4eeb8ad209bf05da2872",
},
).then((
response,
) {
net.onNewWeatherResponse(response.body);
}, onError: (error) {
net.onError(error);
}).whenComplete(
client.close,
);
}
}
/**
* 用来回调成功和失败的结果
*/
abstract class NetListener {
//实况天气
void onNewWeatherResponse(String body);
//三天预报
void onForecastResponse(String body);
void onError(error);
}
调用方式
import 'dart:async';
import 'package:flutter/material.dart';
import 'HttpUtil.dart';
void main(){
runApp(new MaterialApp(
title: 'input',
home: new Scaffold(
appBar: new AppBar(title: new Text('输入事件'),),
body: new MyWeather(),
),
));
}
class MyWeather extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return new MyWeatherState();
}
}
class MyWeatherState extends State<MyWeather> with NetListener{
var weather = 'delay';
HttpManager httpManager = new HttpManager();
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Container(
child: new Column(
children: <Widget>[
new RaisedButton(
child: new Text('三天的预报'),
onPressed: (){
_getWeatherForecast();
}),
new RaisedButton(
child: new Text('获取实时天气'),
onPressed: (){
_getWeatherNewWeather();
}),
new Expanded(
child: new Center(
child: new ListView(
children: <Widget>[
new Text('$weather')
],
),
)
)
],
),
);
}
/**
* 获取三天的预报
*/
_getWeatherForecast() async {
print('请求获取三天的预报');
await httpManager.getForecast(this, '朝阳区');
}
/**
* 获取实况天气
*/
_getWeatherNewWeather() async {
await httpManager.getNewWeather(this, "浦东新区");
}
/**
* 获取实况天气
*/
@override
void onNewWeatherResponse(String body) {
weather = body;
setState(() {});
}
@override
void onError(error) {
// TODO: implement onError
}
@override
void onForecastResponse(String body) {
print('响应获取三天的预报');
weather = body;
setState(() {});
}
}
结果图: