flutter

Flutter集成到原有Android项目

2019-04-25  本文已影响1人  习惯了_就好

1.创建 Flutter Module

进入到原有项目所在的目录,在同级目录执行 flutter create -t module my_flutter ,生成一个flutter module。

2.在原有项目的app的build文件添加一下设置

compileOptions {
  sourceCompatibility 1.8
  targetCompatibility 1.8
}

3.添加依赖

首先在项目的setting文件下添加如下代码:

// MyApp/settings.gradle
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
))                                                                      // new

然后在app的build问价添加依赖:

implementation project(':flutter')

添加完后,可能会运行报错:

Error:Execution failed for task ':app:preAbcdDebugBuild'.
> Android dependency 'com.android.support:support-v4' has different version for the compile (23.4.0) and runtime (27.1.1) classpath. You should manually set the same version via DependencyResolution

这时,将我们原来项目的minSdkVersion等改成和flutter module一样就行了。

4.在原生页面使用

public class FlutterShowActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View flutterView = Flutter.createView(
                FlutterShowActivity.this,
                getLifecycle(),
                "route1*123*router"//路由信息,可以传递到flutter,判断显示什么组件,也可以传递一些简单的数据
        );
        setContentView(flutterView);
    }
}

5.在flutter页面根据原生页面传过来的值处理页面

import 'package:flutter/material.dart';
import 'dart:ui';//导入dart:ui才能使用window

void main() => runApp(MyApp(title: window.defaultRouteName));

class MyApp extends StatelessWidget {
  final String title;

  MyApp({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text("原生跳转flutter"),
        ),
        body: Center(
          child: Text(title),
        ),
      ),
    );
  }
}

6.经过以上步骤项目就可以正常运行了。不过flutter项目和原生项目在同级,操作不方便,可以把flutter项目放到原生项目里面。setting文件修改如下:

//用于初始化以及工程树的配置的
include ':app'
setBinding(new Binding([gradle: this]))                                 // new
evaluate(new File(                                                      // new
        settingsDir,                                               // new
        'flutter/my_flutter/.android/include_flutter.groovy'                          // new
))

需要在原生项目下新建文件夹,然后把flutter项目放到新建的文件夹下,直接把flutter项目放到原生项目下会报错。

官方地址:https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps

上一篇下一篇

猜你喜欢

热点阅读