Flutter实战(一)写一个天气查询的APP
先上效果圖;
代碼github地址:github.com/koudle/GDG_…
1.創(chuàng)建工程
在Android Studio中,File?->?New?->New Flutter Project?->?Flutter Application
創(chuàng)建完工程后,有三個(gè)目錄
android:Android工程的目錄
ios:iOS工程的目錄
lib: Flutter工程的目錄
其中android、ios下的文件我們都不動(dòng),我們只改動(dòng)lib目錄下的dart文件。
2.運(yùn)行Flutter工程
- 這里不建議用模擬器,因?yàn)槟M器在用GPU渲染時(shí)可能會(huì)出問題,導(dǎo)致圖片渲染不出來。
3.天氣API接口申請(qǐng)
注冊(cè)地址console.heweather.com/register
注冊(cè)完后,再看API文檔?www.heweather.com/documents
demo這里用的是,獲取當(dāng)天天氣情況的API:www.heweather.com/documents/a…
用的請(qǐng)求URL如下:
https://free-api.heweather.com/s6/weather/now?location=廣州&key=******4.界面編寫
在創(chuàng)建的工程里,有個(gè)main.dart里面有一段顯示界面的代碼如下:
class MyApp extends StatelessWidget {// This widget is the root of your application.@overrideWidget build(BuildContext context) {return MaterialApp(title: 'Flutter Demo',theme: ThemeData(// This is the theme of your application.//// Try running your application with "flutter run". You'll see the// application has a blue toolbar. Then, without quitting the app, try// changing the primarySwatch below to Colors.green and then invoke// "hot reload" (press "r" in the console where you ran "flutter run",// or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the// counter didn't reset back to zero; the application is not restarted.primarySwatch: Colors.blue,),home: MyHomePage(title: 'Flutter Demo Home Page'),);} }其中home?就是要顯示的界面,這里我們要把MyHomePage換成我們自己的。
4.1 創(chuàng)建WeatherWidget
通過?new?->?Dart File?在lib目錄下創(chuàng)建WeatherWidget
class WeatherWidget extends StatefulWidget{@overrideState<StatefulWidget> createState() {// TODO: implement createStatereturn new WeatherState();} }class WeatherState extends State<WeatherWidget>{@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Scaffold();} }創(chuàng)建完后,在main.dart中將home改為WeatherWidget,如下:
class MyApp extends StatelessWidget {// This widget is the root of your application.@overrideWidget build(BuildContext context) {return MaterialApp(title: 'Flutter Demo',theme: ThemeData(primarySwatch: Colors.blue,),home: WeatherWidget(),);}4.2 HotReload
在寫UI的工程中,我們可以用到Flutter的hot reload的特性,寫布局的時(shí)候,按ctrl+s或cmd+s就可以在手機(jī)上實(shí)時(shí)看到界面的變化。
這個(gè)功能很好用。
4.3添加圖片資源
Flutter可以添加不同的資源,例如圖片、文本、配置文件、靜態(tài)數(shù)據(jù)等。
添加資源時(shí),需要在pubspec.yaml文件中的flutter屬性下添加assets,并標(biāo)明要添加資源的路徑,例如,我們要加入指定的圖片時(shí),可以這么寫:
flutter:assets:- assets/my_icon.png- assets/background.png如果要添加的資源太多,也可以添加文件夾,例如:
flutter:assets:- assets/在本demo中,要添加一個(gè)背景圖,我們?cè)诠こ痰母夸浵聞?chuàng)建images目錄,將背景圖放在images目錄下,然后在pubspec.yaml中添加:
flutter:# The following line ensures that the Material Icons font is# included with your application, so that you can use the icons in# the material Icons class.uses-material-design: trueassets:- images/4.4 寫WeatherWidget的UI布局
在Scaffold中添加body的屬性,來寫UI的布局,如下:
class WeatherState extends State<WeatherWidget>{@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Scaffold(body: new Stack(fit: StackFit.expand,children: <Widget>[new Image.asset("images/weather_bg.jpg",fit: BoxFit.fitHeight,),new Column(mainAxisAlignment: MainAxisAlignment.start,crossAxisAlignment: CrossAxisAlignment.center,children: <Widget>[new Container(width: double.infinity,margin: EdgeInsets.only(top: 40.0),child: new Text("廣州市",textAlign: TextAlign.center,style: new TextStyle(color: Colors.white,fontSize: 30.0,),),),new Container(width: double.infinity,margin: EdgeInsets.only(top: 100.0),child: new Column(children: <Widget>[new Text("20 °",style: new TextStyle(color: Colors.white,fontSize: 80.0)),new Text("晴",style: new TextStyle(color: Colors.white,fontSize: 45.0)),new Text("濕度 80%",style: new TextStyle(color: Colors.white,fontSize: 30.0),)],),)],)],),);}}按ctrl+s,在手機(jī)上就可以看到寫好的UI,但這時(shí)候的數(shù)據(jù)是寫死的,下來看如何通過http獲取數(shù)據(jù)。
5.通過http獲取數(shù)據(jù)
要通過http數(shù)據(jù),我們首先要添加http的依賴庫,在pubspec.yaml中的dependencies添加如下:
dependencies:flutter:sdk: flutter# The following adds the Cupertino Icons font to your application.# Use with the CupertinoIcons class for iOS style icons.cupertino_icons: ^0.1.2http: ^0.12.0然后在當(dāng)前工程目錄下運(yùn)行以下命令行:
$ flutter packages get或者在Android Stuido 打開pubspec.yaml?文件,點(diǎn)擊上面的packages get
這里操作的意義是,拉取http的庫。
5.1 創(chuàng)建WeatherData類
通過?new?->?Dart File?在lib目錄下創(chuàng)建WeatherData
class WeatherData{String cond; //天氣String tmp; //溫度String hum; //濕度WeatherData({this.cond, this.tmp, this.hum});factory WeatherData.fromJson(Map<String, dynamic> json) {return WeatherData(cond: json['HeWeather6'][0]['now']['cond_txt'],tmp: json['HeWeather6'][0]['now']['tmp']+"°",hum: "濕度 "+json['HeWeather6'][0]['now']['hum']+"%",);}factory WeatherData.empty() {return WeatherData(cond: "",tmp: "",hum: "",);} }5.2 數(shù)據(jù)獲取
class WeatherState extends State<WeatherWidget>{WeatherData weather = WeatherData.empty();WeatherState(){_getWeather();}void _getWeather() async{WeatherData data = await _fetchWeather();setState((){weather = data;});}Future<WeatherData> _fetchWeather() async{final response = await http.get('https://free-api.heweather.com/s6/weather/now?location=廣州&key=ebb698e9bb6844199e6fd23cbb9a77c5');if(response.statusCode == 200){return WeatherData.fromJson(json.decode(response.body));}else{return WeatherData.empty();}}@overrideWidget build(BuildContext context) {...} }5.3 將之前寫死的數(shù)據(jù)換成WeatherData
... child: new Column(children: <Widget>[new Text(weather?.tmp,style: new TextStyle(color: Colors.white,fontSize: 80.0)),new Text(weather?.cond,style: new TextStyle(color: Colors.white,fontSize: 45.0)),new Text(weather?.hum,style: new TextStyle(color: Colors.white,fontSize: 30.0),)],),...至此這款天氣查詢的APP實(shí)現(xiàn)了一個(gè)顯示城市、溫度、天氣、濕度的界面,但是這個(gè)界面只有一個(gè)顯示的功能,沒有任何可交互的地方,寫下篇文章繼續(xù)完善查詢天氣的APP的功能。
歡迎加入學(xué)習(xí)交流群;964557053。進(jìn)群可免費(fèi)領(lǐng)取一份最新技術(shù)大綱和Android進(jìn)階資料。請(qǐng)備注csdn
總結(jié)
以上是生活随笔為你收集整理的Flutter实战(一)写一个天气查询的APP的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Spring Boot】1.基础知识
- 下一篇: ES6 Generator async