首先需要說明本次博客我是用的電腦是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的博客