Flutter混合Android

juexingzhe發表於2019-04-10

1.新建一個Android工程

比如工程名MyApplication

2.建立Flutter Module

在cd到當前project下執行命令:

E:\MyApplication
flutter create -t module my_flutter
複製程式碼

3.增加配置程式碼

在工程setttings.gradle中增加配置:

include ':app'
setBinding(new Binding([gradle: this]))
evaluate(new File(settingsDir, 'my_flutter/.android/include_flutter.groovy'))
複製程式碼

接下來在app的build.gradle增加依賴:

implementation project(':flutter')
複製程式碼

可能會報錯:

Error: Invoke-customs are only supported starting with Android O (--min-api 26)
複製程式碼

在app的build.gradleandroid標籤下增加:

compileOptions{
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
}
複製程式碼

最後生成的目錄結構:

Android混合Flutter.PNG

經過上面3步就已經整合Flutter了,接著看看怎麼在Android工程中建立Flutter的UI

4.Android中建立Flutter UI

Flutter提供兩種方法引入,一個是View,一個是Fragment,看下View的程式碼:

public class FlutterActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flutter);

        FlutterView view = Flutter.createView(this, getLifecycle(), "new_page");
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT
        );
        addContentView(view, layoutParams);
    }
}
複製程式碼

第二個引數是Lifecycle物件,第三個引數是route,這個引數Flutter端可以通過window.defaultRouteName獲取

看下Flutter側的dart程式碼, 在my_flutter->lib目錄下新建list.dart

import 'package:flutter/material.dart';

class ListViewTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Widget divider1 = Divider(color: Colors.blue);
    Widget divider2 = Divider(color: Colors.green);

    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('ListTest'),
      ),
      body: Center(
        child: ListView.separated(
            itemBuilder: (BuildContext context, int index) {
              return ListTile(
                title: Text("$index"),
              );
            },
            separatorBuilder: (BuildContext context, int index) {
              return index % 2 == 0 ? divider1 : divider2;
            },
            itemCount: 100),
      ),
    );
  }
}
複製程式碼

main.dart中匯出路由new_page:

import 'package:flutter/material.dart';
import 'list.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(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
      routes: {
        "new_page": (context) => ListViewTest(),
      },
    );
  }
}
複製程式碼

5.hot reload

進入到flutter module目錄下, 執行命令 flutter attach 即可, 在這個命令視窗按r即可hot reload:

E:\MyApplication\my_flutter
λ flutter attach
Waiting for a connection from Flutter on vivo x27...
Done.
Syncing files to device vivo x27...                             1,125ms

?  To hot reload changes while running, press "r". To hot restart (and rebuild state), press "R".
An Observatory debugger and profiler on vivo 1819 is available at: http://127.0.0.1:55515/
For a more detailed help message, press "h". To detach, press "d"; to quit, press "q".


Initializing hot reload...
Reloaded 2 of 433 libraries in 969ms.
複製程式碼

6.總結

最後對比看下繼承了Flutter和沒有繼承的Android工程打出來的Release包大小對比:

withFlutterApkSize.PNG

withoutFlutterApkSize.PNG

接入Flutter之後,包大小激增5M,主要是因為flutter.so這個so庫。還有flutter_assets裡是flutter工程產生的assets檔案, isolate_snapshot_data、isolate_snapshot_instr、vm_snapshot_data、vm_snapshot_instr為特定平臺的資料和指令.

Refs:

Android工程接入Flutter module

flutter接入現有的app詳細介紹

Flutter(Android 混合開發)

如何進行Flutter混合開發

Flutter 的兩種編譯模式

相關文章