美文网首页
在原生项目中集成Flutter遇到的坑(不定期更新)

在原生项目中集成Flutter遇到的坑(不定期更新)

作者: GIndoc | 来源:发表于2019-03-14 11:31 被阅读0次

    写本文章的目的在于记录在实践过程中遇到的问题,因为我发现很多文章都是一样的,当我照着其他文章的教程实践时,出现了一些问题。因此在这里记录一下:

    1.在原项目中以module的方式集成flutter,在setting.gradle中添加

    setBinding(new Binding([gradle: this]))
    evaluate(new File(
            settingsDir.parentFile,                         
            'my_flutter/.android/include_flutter.groovy'
    ))
    

    出现问题

    * What went wrong:
    A problem occurred evaluating settings 'xxx'.
    > /Users/gindoc/Desktop/my_flutter/.android/include_flutter.groovy 
    (/Users/gindoc/Desktop/my_flutter/.android/include_flutter.groovy)
    

    你会发现你的flutter 模块名前面不是项目根目录

    解决办法:

    如果你创建的flutter moduel是作为原应用的子mudule,则为不需要在settingsDir后面加.parentFile,即

    setBinding(new Binding([gradle: this]))
    evaluate(new File(
            settingsDir,                         
            'my_flutter/.android/include_flutter.groovy'
    ))
    

    2.在编写完Flutter代码后,运行报错,可以通过命令行flutter analyze查看错误信息。

    3.由于我是在AndroidX的项目下集成flutter的,而用flutter create -t module <module name>方式创建的module里面的Android项目是依赖support包的,所以需要做一些修改。

    方案来自https://github.com/flutter/flutter/issues/23586
    具体步骤如下
    1、打开flutter module里面的.android目录下的gradle.properties,添加

    android.enableJetifier=true
    android.useAndroidX=true
    

    2、将.android目录下的build.gradle的build tool版本改为3.3.1,即

    buildscript {
      ...
      dependencies {
        classpath "com.android.tools.build:gradle:3.3.1"
        ...
      }
      ...
    }
    

    3、将.android目录下app里面的build.gradle的targetSdkVersion修改为28

    android {
      defaultConfig {
        ...
        targetSdkVersion 28
      }
      ...
    }
    

    4、MissingPluginException(No implementation found for method getBatteryLevel on channel samples.flutter.io/battery)

    在尝试在flutter中与原生交互(比如获取手机电量,跳转原生页面)时,出现MissingPluginException。
    出现这种情况的原因是因为plugin没有注册成功

    这里需要注意的是: 1、每个flutterView所在的Activity都要注册plugin,否则就可能出现这种情况。 2、给activity添加flutterView的操作要在注册plugin之前

    示例:

    // 这里定义一个基类BaseActivity,因为
    // 1、我们注册plugin需要PluginRegistry,
    // 2、添加flutterView需要lifecycle或者supportFragmentManager,
    // 而 FlutterActivity 和 FragmentActivity 都不能同时满足以上两个条件
    
    abstract class BaseActivity :AppCompatActivity(), FlutterView.Provider, PluginRegistry, FlutterActivityDelegate.ViewFactory{
    
        private val delegate = FlutterActivityDelegate(this, this)
        private val eventDelegate: FlutterActivityEvents
        private val viewProvider: FlutterView.Provider
        private val pluginRegistry: PluginRegistry
    
        init {
            this.eventDelegate = this.delegate
            this.viewProvider = this.delegate
            this.pluginRegistry = this.delegate
        }
    
    
        override fun getFlutterView(): FlutterView {
            return this.viewProvider.flutterView
        }
    
        override fun createFlutterView(context: Context): FlutterView? {
            return null
        }
    
        override fun createFlutterNativeView(): FlutterNativeView? {
            return null
        }
    
        override fun retainFlutterNativeView(): Boolean {
            return false
        }
    
        override fun hasPlugin(key: String): Boolean {
            return this.pluginRegistry.hasPlugin(key)
        }
    
        override fun <T> valuePublishedByPlugin(pluginKey: String): T {
            return this.pluginRegistry.valuePublishedByPlugin(pluginKey)
        }
    
        override fun registrarFor(pluginKey: String): PluginRegistry.Registrar {
            return this.pluginRegistry.registrarFor(pluginKey)
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            this.eventDelegate.onCreate(savedInstanceState)
        }
    
        override fun onStart() {
            super.onStart()
            this.eventDelegate.onStart()
        }
    
        override fun onResume() {
            super.onResume()
            this.eventDelegate.onResume()
        }
    
        override fun onDestroy() {
            this.eventDelegate.onDestroy()
            super.onDestroy()
        }
    
        override fun onBackPressed() {
            if (!this.eventDelegate.onBackPressed()) {
                super.onBackPressed()
            }
    
        }
    
        override fun onStop() {
            this.eventDelegate.onStop()
            super.onStop()
        }
    
        override fun onPause() {
            super.onPause()
            this.eventDelegate.onPause()
        }
    
        override fun onPostResume() {
            super.onPostResume()
            this.eventDelegate.onPostResume()
        }
    
        override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
            this.eventDelegate.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            if (!this.eventDelegate.onActivityResult(requestCode, resultCode, data)) {
                super.onActivityResult(requestCode, resultCode, data)
            }
    
        }
    
        override fun onNewIntent(intent: Intent) {
            this.eventDelegate.onNewIntent(intent)
        }
    
        public override fun onUserLeaveHint() {
            this.eventDelegate.onUserLeaveHint()
        }
    
        override fun onTrimMemory(level: Int) {
            this.eventDelegate.onTrimMemory(level)
        }
    
        override fun onLowMemory() {
            this.eventDelegate.onLowMemory()
        }
    
        override fun onConfigurationChanged(newConfig: Configuration) {
            super.onConfigurationChanged(newConfig)
            this.eventDelegate.onConfigurationChanged(newConfig)
        }
    }
    
    // FlutterView所在的Activity
    class FlutterPageActivity : BaseActivity() {
    
        private val CHANNEL = "samples.flutter.io/battery"
    
        override fun onCreate(savedInstanceState: Bundle?) {
            FlutterMain.startInitialization(applicationContext)
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            // 1、创建flutterView
            val flutterView = Flutter.createView(this, lifecycle, "route1")
            val layout =
                FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
            addContentView(flutterView, layout)
    
            // 2、注册plugin
            GeneratedPluginRegistrant.registerWith(this)
            MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
                // 在这里和原生交互
                if (call.method == "getBatteryLevel") {
                    val batteryLevel = getBatteryLevel()
    
                    if (batteryLevel != -1) {
                        result.success(batteryLevel)
                    } else {
                        result.error("UNAVAILABLE", "Battery level not available.", null)
                    }
                    startActivity(Intent(this@FlutterPageActivity, NativeActivity::class.java))                    // 跳转原生界面
                } else {
                    result.notImplemented()
                }
            }
    
    
        }
    
        // 获取电量
        private fun getBatteryLevel(): Int {
            var batteryLevel = -1
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
                batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
            } else {
                val intent =
                    ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
                batteryLevel =
                    intent!!.getIntExtra(
                        BatteryManager.EXTRA_LEVEL,
                        -1
                    ) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
            }
    
            return batteryLevel
    
        }
    
    }
    
    
    

    另外这里推荐以https://www.cnblogs.com/fuyaozhishang/p/9617234.html该博客的方式集成Android和Flutter,进行混合开发,达到原生开发和Flutter开发互不干扰。

    相关文章

      网友评论

          本文标题:在原生项目中集成Flutter遇到的坑(不定期更新)

          本文链接:https://www.haomeiwen.com/subject/dcgfmqtx.html