flutter添加到android原生

2021-12-29 16:25:47 浏览数 (1)

1.创建一个flutter module
代码语言:txt复制
flutter create -t module --org com.example my_flutter
2.在原生build.gradle下
代码语言:txt复制
android {
  //...
  compileOptions {
    sourceCompatibility 1.8
    targetCompatibility 1.8
  }
}
3.添加Flutter模块作为依赖项

有两种方式

######(1)无需安装flutter sdk

Flutter库打包为由AAR和POM工件组成的通用本地Maven存储库,

######(2) 需要安装sdk

原生settings.gradle下添加

代码语言:txt复制
// Include the host app project.
include ':app'                                    // assumed existing content
setBinding(new Binding([gradle: this]))                                // new
evaluate(new File(                                                     // new
  settingsDir.parentFile,                                              // new
  'my_flutter/.android/include_flutter.groovy'                         // new
))  

原生build.gradle下

代码语言:txt复制
dependencies {
  implementation project(':flutter')
}
4.AndroidManifest.xml
代码语言:txt复制
<activity
  android:name="io.flutter.embedding.android.FlutterActivity"
  android:theme="@style/LaunchTheme"
  android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
  android:hardwareAccelerated="true"
  android:windowSoftInputMode="adjustResize"
  />

@style/LaunchTheme 修改

5.启动
代码语言:txt复制
package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        FlutterActivity.createDefaultIntent(this)
        startActivity(
            FlutterActivity
                .withNewEngine()
                .initialRoute("/")
                .build(this)
        )
    }
}

0 人点赞