我的第一個Flutter APP
首先需要說明本次部落格我是用的電腦是mac,並且在下沒有使用科學上網,額,對使用window的同學不太友好,日後再來一篇window配置Flutter環境的部落格
1.環境配置
關於環境配置,我是根據範玉剛大神的部落格做的 (https://blog.csdn.net/singwhatiwanna/article/details/79571364),我自己在進行一些補充
在我們執行flutter doctor時,可能會說我們那些東西沒安裝,而你如果安裝,但是他卻不知道,可能你環境沒有配置,需要在mac配置路徑,比如設定Android SDK環境變數,請參考如下部落格,親測有效
https://blog.csdn.net/free_co/article/details/77115920
還有就是記得Android Studio的版本一定要在3.0以上,要不然Flutter外掛安裝後執行有問題,並且如果你搜索不到Flutter外掛,那就百度
2.建立工程
在我們執行完flutter doctor命令並且在Android Studio裡安裝Flutter外掛後,我們 File->new ->new Flutter project
然後我們選擇手機或者模擬器,並且工程選擇main.dart(只有一個),點選三角形安裝app到手機上。可能會執行失敗,因為一些依賴包可能會獲取失敗,這個我就是當前試了一次沒成功,第二天早上一試成功了
我們建立的預設Flutter工程是一個能夠計算我們點選按鈕並且顯示點選次數的程式
3.分析工程檔案和程式碼(假裝自己看得懂)
我們看看這個預設Flutter工程的資料夾和程式碼
首先看看android和ios資料夾的內容
android資料夾裡一個很規範的Android Studio所建立的Android app工程,但是裡面的MainActivity的程式碼和平常的不同
public class MainActivity extends FlutterActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GeneratedPluginRegistrant.registerWith(this); } }
我們再來看看GeneratedPluginRegistrant這個類,它在註釋裡說他是一個自動生成的檔案,不要編輯他,
/**
* Generated file. Do not edit.
*/
public final class GeneratedPluginRegistrant {
public static void registerWith(PluginRegistry registry) {
if (alreadyRegisteredWith(registry)) {
return;
}
}
private static boolean alreadyRegisteredWith(PluginRegistry registry) {
final String key = GeneratedPluginRegistrant.class.getCanonicalName();
if (registry.hasPlugin(key)) {
return true;
}
registry.registrarFor(key);
return false;
}
}
我們再來看看ios,也是一箇中軌中軌的ios工程
在Runner裡的AppDelegate.h的程式碼也是使用的GeneratedPluginRegistrant,預設生成的類,同樣的,GeneratedPluginRegistrant在註釋裡說是自動生成,不要改動
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
最後我們可以確定一個件事那就是這個app真正的實現的地方是lib資料夾的main.dart
這是佈局程式碼
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
可以看得出來這語言類似Kotlin,然後在floatingActionButton裡可以看得到綁定了一個_incrementCounter函式為點選事件觸發的函式,對於setState我認為是類似在其內部程式碼塊執行完後,重新生成介面的觸發函式
void _incrementCounter() {
setState(() {
_counter++;
});
}
這篇部落格算是寫完了,後期會繼續寫Flutter的部落格