本文将学习一个新内容 http 这个炒鸡感兴趣吧?
使用http我们需要添加插件
http: ^0.11.3+16
这个写法的意思就是 >=0.11.19 <0.12.0
这里我们使用和风天气的API接口来做测试,因为最后我们的天气预报demo也是使用这个api,比较简单
实现效果点击按钮 通过http请求实况天气,并显示请求结果,
效果如下:
main.dart:
import 'dart:async';
/**
*http
*/
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:myweather/httpListener/http.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() => new MyWeatherState();
}
class MyWeatherState extends State<MyWeather> with NetListener {
var weather = "delay" ;
httpManager manager = new httpManager();
@override
Widget build(BuildContext context) {
return new Container(
child: new Column(
children: <Widget>[
new RaisedButton(
child: new Text("获取实时天气"),
onPressed: () {
_getWeather();
},
),
new Expanded(
child: new Center(
child: new Text("$weather"),
)),
],
),
);
}
/**
* 获取三天的预报 and 天气实况
*/
_getWeather() async {
await manager.getForecast(this, "闵行区");
await manager.getNewWeather(this, "浦东新区");
}
@override
void onError(error) {print("$error");}
@override
void onForecastResponse(String body) {
}
/**
* 获取实况天气
*/
@override
void onNewWeatherResponse(String body) {
weather = body;
setState(() {});
}
}
然后再创建一个dart文件用来放http请求的代码,名字就叫http.dart
http.dart:
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);
}
没啥难的吧…至于json解析等在后面我们也会学习到