这是一个使用flutter写的天气预报APP,主要使用了如下几个插件,入门级练练手。 dio
:网络请求插件,用于获取天气信息 fluttertoast
:弹出toast提示信息 shared_preferences
:简单的数据存储,用于保存设置过的天气预报信息 intl
:日期格式化 项目GitHub地址:d9l_weathergit
首先搜集一些天气预报APP的设计稿,肯定一下本身的界面。看到有不少好看的,可是并不想作的太复杂。因而选择了一些简洁的,背景图也都去掉了。而后在PS里大概出一个界面,以下: github
页面都写好以后就须要把数据替换成真实数据了,这里使用了和风天气的API获取天气数据,注册以后就能使用。可是普通用户有些接口是不能用的,可是对这个APP来讲,可以查到天气信息以及足够了。 新建一个dio_client.dart
文件,里面放全部API请求方法,这里写成单例模式,以下。网络
class DioClient {
factory DioClient() => _getInstance();
static DioClient get instance => _getInstance();
static DioClient _instance; // 单例对象
static DioClient _getInstance() {
if (_instance == null) {
_instance = DioClient._internal();
}
return _instance;
}
DioClient._internal();
}
复制代码
在main函数中初始化单例对象app
DioClient();
复制代码
使用方法async
DioClient().getRealTimeWeather();
复制代码
如获取实时天气的方法以下:函数
Future<RealTimeWeather> getRealTimeWeather(String cid) async {
String url = rootUrl + '/now';
try {
Response response = await Dio().get(url, options: options, queryParameters: {
'location': cid, // 查询的城市id
'key': key,
});
// 根据API返回的参数定义的model
RealTimeWeather realTimeWeather;
realTimeWeather = RealTimeWeather.fromJson(response.data['HeWeather6'].first);
if (realTimeWeather.status.contains('permission')) {
return realTimeWeather;
}
realTimeWeather.basic = Basic.fromJson(realTimeWeather.mBasic);
realTimeWeather.update = Update.fromJson(realTimeWeather.mUpdate);
realTimeWeather.now = Now.fromJson(realTimeWeather.mNow);
return realTimeWeather;
} catch (e) {
print('getRealTimeWeather error= $e');
return null;
}
}
复制代码
在搜索完一个城市的天气后,须要把这个城市的id
保存在shared_preferences
中,这样关闭app下次再打开的时候才能显示上一次查询的城市天气,或者须要保存多个城市天气预报的时候,也能够保存。 保存只须要一行代码:布局
SpClient.sp.setString('cid', cid);
复制代码
shared_preferences
的使用也是使用了单例模式,和dio_client.dart
同样ui
这个项目很简单,也只是用了不多的东西,主要是练练手吧。也没太多东西可以介绍的。后面有时间的话会继续完善,好比加上国际化、使用状态管理,多城市保存等等。感兴趣的能够关注一下。GitHub给star支持,谢谢! 最后再放一下本项目的GitHub地址 d9l_weatherurl