Flutter開發環境搭建和調試


Flutter開發工具很多,有很多支持Flutter開發的IDE。比如Android Studio、Visual Studio Code、InteIIiJ IDEA、Atom、Komodo等。這裏將使用Visual Studio Code作爲主要開發工具,因爲Visual Studio Code佔用內存和CPU比較低,非常的流暢,體驗也比較的好。模擬器的話,這裏推薦使用Android官方的模擬器,也就是Android Studio SDK裏帶的模擬器。不過,這裏的模擬器我們使用單獨啓動的,無需從Android Studio啓動,當然也可以用真機運行調試。接下來,我們就開始Flutter開發環境的搭建吧。注意:本文是在Windows環境下安裝的開發環境。本文將主要介紹:

  • Flutter下載與環境變量配置
  • Visual Studio Code插件安裝與新建Flutter項目
  • 模擬器的安裝
  • 運行Flutter項目到模擬器和真機
  • Flutter常用命令

開發環境的搭建

1. 下載Flutter SDK

Flutter SDK由兩部分構成,一個是Dart SDK,另一個就是Flutter SDK,因爲Flutter是基於Dart的。可以通過兩種方式下載:一種是Git下載;另一種是直接下載SDK壓縮包即可。
Git方式我們可以通過拉取官方Github上的flutter分支來下載。分支分類如下圖:
Flutter分支
可以看到主要有dev、beta和stable三個官方分支使,這裏正式開發的話可以下載stable穩定版本。用Git命令進行下載stable分支:

git clone -b stable https://github.com/flutter/flutter.git

另一種是直接官網下載SDK壓縮包,官方下載地址爲:

https://storage.googleapis.com/flutter_infra/releases/stable/windows/flutter_windows_v1.0.0-stable.zip

2. 配置環境變量

下載完SDK後我們可以把它解壓放到指定文件夾裏,接下來就是配置SDK環境變量量,這樣我們就可以在需要的目錄執行相關命令了。如果在官網更新下載SDK慢的話,可以設置國內的鏡像代理地址,這樣下載會快一些。可以將如下的國內下載鏡像地址加入到環境變量中:

變量名:PUB_HOSTED_URL,變量值:https://pub.flutter-io.cn
變量名:FLUTTER_STORAGE_BASE_URL,變量值:https://storage.flutter-io.cn

Flutter SDK環境變量,講flutter的bin目錄加入環境變量即可:

[你的Flutter文件夾路徑]\flutter\bin

這樣我們的Flutter SDK的環境變量就配置完畢了。接下來在命令提示符窗口中輸入命令:

flutter doctor

它可以幫助我們檢查Flutter環境變量是否設置成功,Android SDK是否下載以及配置好環境變量等等。如果有相關的錯誤提示,根據提示進行修復和安裝、設置即可。每次運行這個命令,都會幫你檢查是否缺失了必要的依賴。通過運行flutter doctor命令來驗證你是否已經正確地設置了,並且可以自動更新和下載相關的依賴。如果全部配置正確的話,會出現如下類似的檢測信息:

Flutter配置檢查
主要檢測信息爲:Flutter、Android toolchain、Connected device。

3.安裝Visual Studio Code所需插件

在Visual Studio Code的Extensions裏搜索安裝Dart和Flutter擴展插件:
Flutter插件安裝
安裝完成插件後,重啓Visual Studio Code編輯器即可。

4.創建Flutter項目

接下來進行Flutter項目的新建,我們可以通過命令面板或者快捷鍵Ctrl+Shif+P打開命令面板,找到Flutter:New Project:
Flutter新建項目
點擊New Project,接下來進入項目名稱輸入:
輸入Flutter項目名稱
回車,然後選擇好項目的存儲位置即可,這樣就完成了Flutter項目的新建。
整個的創建流程日誌如下:

[undefined] flutter create .
Waiting for another flutter command to release the startup lock...
Creating project ....
  .gitignore (created)
  .idea\libraries\Dart_SDK.xml (created)
  .idea\libraries\Flutter_for_Android.xml (created)
  .idea\libraries\KotlinJavaRuntime.xml (created)
  .idea\modules.xml (created)
  .idea\runConfigurations\main_dart.xml (created)
  .idea\workspace.xml (created)
  .metadata (created)
  android\app\build.gradle (created)
  android\app\src\main\java\com\example\fluttersamples\MainActivity.java (created)
  android\build.gradle (created)
  android\flutter_samples_android.iml (created)
  android\app\src\main\AndroidManifest.xml (created)
  android\app\src\main\res\drawable\launch_background.xml (created)
  android\app\src\main\res\mipmap-hdpi\ic_launcher.png (created)
  android\app\src\main\res\mipmap-mdpi\ic_launcher.png (created)
  android\app\src\main\res\mipmap-xhdpi\ic_launcher.png (created)
  android\app\src\main\res\mipmap-xxhdpi\ic_launcher.png (created)
  android\app\src\main\res\mipmap-xxxhdpi\ic_launcher.png (created)
  android\app\src\main\res\values\styles.xml (created)
  android\gradle\wrapper\gradle-wrapper.properties (created)
  android\gradle.properties (created)
  android\settings.gradle (created)
  ios\Runner\AppDelegate.h (created)
  ios\Runner\AppDelegate.m (created)
  ios\Runner\main.m (created)
  ios\Runner.xcodeproj\project.pbxproj (created)
  ios\Runner.xcodeproj\xcshareddata\xcschemes\Runner.xcscheme (created)
  ios\Flutter\AppFrameworkInfo.plist (created)
  ios\Flutter\Debug.xcconfig (created)
  ios\Flutter\Release.xcconfig (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Contents.json (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-1024x1024@1x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-20x20@1x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-20x20@2x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-20x20@3x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-29x29@1x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-29x29@2x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-29x29@3x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-40x40@1x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-40x40@2x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-40x40@3x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-60x60@2x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-60x60@3x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-76x76@1x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-76x76@2x.png (created)
  ios\Runner\Assets.xcassets\AppIcon.appiconset\Icon-App-83.5x83.5@2x.png (created)
  ios\Runner\Assets.xcassets\LaunchImage.imageset\Contents.json (created)
  ios\Runner\Assets.xcassets\LaunchImage.imageset\LaunchImage.png (created)
  ios\Runner\Assets.xcassets\LaunchImage.imageset\LaunchImage@2x.png (created)
  ios\Runner\Assets.xcassets\LaunchImage.imageset\LaunchImage@3x.png (created)
  ios\Runner\Assets.xcassets\LaunchImage.imageset\README.md (created)
  ios\Runner\Base.lproj\LaunchScreen.storyboard (created)
  ios\Runner\Base.lproj\Main.storyboard (created)
  ios\Runner\Info.plist (created)
  ios\Runner.xcodeproj\project.xcworkspace\contents.xcworkspacedata (created)
  ios\Runner.xcworkspace\contents.xcworkspacedata (created)
  lib\main.dart (created)
  flutter_samples.iml (created)
  pubspec.yaml (created)
  README.md (created)
  test\widget_test.dart (created)
Running "flutter packages get" in flutter_samples...            11.8s
Wrote 64 files.

All done!
[] Flutter is fully installed. (Channel stable, v1.0.0, on Microsoft Windows [Version 10.0.17134.590], locale zh-CN)
[] Android toolchain - develop for Android devices is fully installed. (Android SDK 28.0.3)
[] Android Studio is fully installed. (version 3.3)
[] IntelliJ IDEA Community Edition is fully installed. (version 2018.3)
[!] Connected device is not available.

Run "flutter doctor" for information about installing additional components.

In order to run your application, type:

  $ cd .
  $ flutter run

Your application code is in .\lib\main.dart.

exit code 0

Flutter項目結構如下:
Flutter項目結構
其中,Android相關的修改和配置在android目錄下,結構和Android應用項目結構一樣;IOS相關修改和配置在ios目錄下,結構和IOS應用項目結構一樣。最重要的flutter代碼文件是在lib目錄下,類文件以.dart結尾,語法結構爲Dart語法結構。大致如下:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

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 simply save your changes to "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'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

模擬器的安裝與調試

項目新建完畢了,接下來就是編譯運行Flutter項目到真機或者模擬器了。先說模擬器,模擬器在我們下載的Android SDK的目錄裏,可以通過兩種方法創建模擬器,推薦在Android Studio裏新建一個模擬器,點擊進入AVD Manager,如果沒有模擬器的話,就創建一個即可,可以選擇最新的SDK:
AVD Manager模擬器列表
創建完畢後,我們就可以在電腦的模擬器目錄看到我們創建的模擬器裏:
已創建的模擬器列表
對應的模擬器AVD Manager相關也在Android SDK目錄下:
SDK裏的模擬器所在目錄
接下來我們就可以關閉相關窗口了,建立一個bat文件,寫入啓動模擬器的命令,這樣每次啓動模擬器直接運行這個bat文件即可:

D:\Sdk\emulator\emulator.exe -avd Pixel_XL_API_28

模擬器所在的SDK目錄根據你的實際情況位置修改即可。
快速運行模擬器的命令文件
接下來,雙擊這個bat文件運行模擬器:
啓動模擬器
接着在項目所在目錄運行flutter run命令即可編譯運行flutter項目到模擬器上:
啓動模擬器日誌
運行效果如下圖:
Flutter Demo模擬器運行效果
運行成功後,後續運行調試只要不退出應用界面,就可以進行熱重載,輸入r進行熱重載當前頁面,輸入R進行整個應用的熱重啓,輸入h彈出幫助信息,輸入d解除關聯,輸入q退出應用調試。如果遇到有多個模擬器或者模擬器和真機同時存在的話,可以通過-d參數加設備ID指定要運行的設備,例如:

flutter run -d emulator-5556

可以通過flutter devices或adb devices命令查看目前已連接的設備信息。
還有一種命令方式創建模擬器,輸入如下命令可以查看當前可用的模擬器:

flutter emulator

輸入以下命令可以創建指定名稱的模擬器,默認創建的模擬器Android版本號爲已安裝的最新的SDK版本號:

flutter emulators --create --name xyz

運行以下命令可以啓動模擬器:

flutter emulators --launch <emulator id>

替換爲你的模擬器ID名稱即可。
真機設備運行調試和模擬器的過程基本一樣,手機和電腦通過USB連接,手機開啓開發人員選項和USB調試,最後運行flutter run命令即可。
其他常用的命令如下:

flutter build apk;           //打包Android應用
flutter build apk –release;
flutter install;              //安裝應用
flutter build ios;            //打包IOS應用
flutter build ios –release;
flutter clean;               //清理重新編譯項目
flutter upgrade;            //升級Flutter SDK和依賴包
flutter channel;            //查看Flutter官方分支列表和當前項目使用的Flutter分支
flutter channel <分支名>;   //切換分支

好了,Flutter開發環境搭建和調試就爲大家講解到這裏了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章