Android

Android已有原生应用 集成flutter

2018-12-18  本文已影响13人  程序员WW

官方文档 https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps#experiment-turn-the-flutter-project-into-a-module

1.创建flutter module
在Android Studio Terminal中输入 如下

  cd ..
  flutter create -t module <module_name>

在原应用父级目录下创建flutter module,如果想将flutter module当做原应用的子module,则省去cd ..这一步,<module_name>为你的flutter module名

2.为你的app添加flutter module依赖
(1)在原应用的setting.gradle下添加如下代码

setBinding(new Binding([gradle:this]))
evaluate(new File(
    settingsDir.parentFile,  //若做为原应用的子mudule,则为settingsDir
    '<module_name>/.android/include_flutter.groovy'
))

(2)在原应用的build.gradle下的dependencies 添加flutter依赖

compile project(':flutter') 

我的gradle版本较低,用的是compile,高版本用implementation,与原应用保持一致

3.执行sync 没报错就成功了,但是编辑flutter要再打开个窗口,open你的fullter module

4.原生Activity跳转至flutter
在activity中以view的形式加载flutter,参考如下

public class FlutterActivity extends BaseActivity {
    private FlutterView flutterView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tr_activity_empty);
        flutterView= Flutter.createView(this,getLifecycle(),"route1");
        FrameLayout.LayoutParams layout=new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT);
        addContentView(flutterView,layout);
    }
}

在flutter的main.dart中处理路由

import 'dart:ui';
import 'package:flutter/material.dart';

void main() => runApp(_widgetForRoute(window.defaultRouteName));

Widget _widgetForRoute(String route) {
  switch (route) {
    case 'route1':
      return SomeWidget(...);
    case 'route2':
      return SomeOtherWidget(...);
    default:
      return Center(
        child: Text('Unknown route: $route', textDirection: TextDirection.ltr),
      );
  }
}

以下为我遇到的问题

  1. Gradle DSL method not found: 'google()'
    原因:因为我的gradle版本太低,而flutter的gradle版本较高
    解决办法:打开flutter安装目录下 packages/flutter_tools/gradle/flutter.gradle文件,替换 google()为

    maven {
    url 'https://maven.google.com/'
    }

2.Could not download asm-util.jar
打开settring../ Build../Gradle 取消 offline work选项

3.buildToolsVersion等版本问题
将flutter module下 .android /Flutter/build.gradle下相关版本设置与原应用
保持一致

上一篇下一篇

猜你喜欢

热点阅读