天天看點

Flutter實戰(一)寫一個天氣查詢的APP

先上效果圖;

代碼github位址:

github.com/koudle/GDG_…

1.建立工程

在Android Studio中,

File

 -> 

New

 ->

New Flutter Project

Flutter Application

建立完工程後,有三個目錄

android

:Android工程的目錄

ios

:iOS工程的目錄

lib

: Flutter工程的目錄

其中android、ios下的檔案我們都不動,我們隻改動lib目錄下的dart檔案。

2.運作Flutter工程

  1. 連接配接手機
  • 這裡不建議用模拟器,因為模拟器在用GPU渲染時可能會出問題,導緻圖檔渲染不出來。
  1. 然後按

    Run

     在手機上把程式跑起來。

3.天氣API接口申請

注冊位址

console.heweather.com/register

注冊完後,再看API文檔 

www.heweather.com/documents

demo這裡用的是,擷取當天天氣情況的API:

www.heweather.com/documents/a…

用的請求URL如下:

https://free-api.heweather.com/s6/weather/now?location=廣州&key=******

           

4.界面編寫

在建立的工程裡,有個

main.dart

裡面有一段顯示界面的代碼如下:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget 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 建立WeatherWidget

通過 

new

Dart File

 在lib目錄下建立WeatherWidget

class WeatherWidget extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new WeatherState();
  }
}

class WeatherState extends State<WeatherWidget>{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
    );
  }            
}

           

建立完後,在

main.dart

中将

home

改為

WeatherWidget

,如下:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: WeatherWidget(),
    );
  }

           

4.2 HotReload

在寫UI的工程中,我們可以用到Flutter的hot reload的特性,寫布局的時候,按

ctrl+s

cmd+s

就可以在手機上實時看到界面的變化。

這個功能很好用。

4.3添加圖檔資源

Flutter可以添加不同的資源,例如圖檔、文本、配置檔案、靜态資料等。

添加資源時,需要在

pubspec.yaml

檔案中的

flutter

屬性下添加

assets

,并标明要添加資源的路徑,例如,我們要加入指定的圖檔時,可以這麼寫:

flutter:
  assets:
    - assets/my_icon.png
    - assets/background.png

           

如果要添加的資源太多,也可以添加檔案夾,例如:

flutter:
  assets:
    - assets/

           

在本demo中,要添加一個背景圖,我們在工程的根目錄下建立

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: true
  assets:
    - images/

           

4.4 寫WeatherWidget的UI布局

Scaffold

中添加

body

的屬性,來寫UI的布局,如下:

class WeatherState extends State<WeatherWidget>{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return 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

,在手機上就可以看到寫好的UI,但這時候的資料是寫死的,下來看如何通過http擷取資料。

5.通過http擷取資料

要通過http資料,我們首先要添加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.2
  http: ^0.12.0

           

然後在目前工程目錄下運作以下指令行:

$ flutter packages get

           

或者在Android Stuido 打開

pubspec.yaml

 檔案,點選上面的

packages get

這裡操作的意義是,拉取http的庫。

5.1 建立WeatherData類

new

Dart File

 在lib目錄下建立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 資料擷取

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();
    }
  }

  @override
  Widget build(BuildContext context) {
    ...
  }
}  

           

5.3 将之前寫死的資料換成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實作了一個顯示城市、溫度、天氣、濕度的界面,但是這個界面隻有一個顯示的功能,沒有任何可互動的地方,寫下篇文章繼續完善查詢天氣的APP的功能。

歡迎加入學習交流群;964557053。進群可免費領取一份最新技術大綱和Android進階資料。請備注csdn

繼續閱讀