Flutter 添加到现有项目(Android)

image.png

环境配置:

AndroidStudio版本: 4.0
flutter环境:

[✓] Flutter (Channel stable, v1.17.1, on Mac OS X 10.15.4 19E287, locale
zh-Hans-CN)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.0)

创建步骤

1、AndroidStudio创建原生Android项目名AndroidHost (支持androidx)
2、然后AndroidStudio 创建一个Flutter modle 名字flutter_module(支持androidx)

注意
如果在编译过程中失败,有可能一些库被墙掉了。
可以在AndroidHost项目build下添加

allprojects {
    repositories {
        google()
        jcenter()
// 被墙掉,flutter.io拉不下来,则添加配置如下
        maven{url 'http://maven.aliyun.com/nexus/content/groups/public/'}
        maven { url "http://download.flutter.io" }
    }
} 

同样在flutter_module的.android项目的build下添加上面那两句。
3、在AndroidHost项目中app下build.gradle中添加

android {
....
    compileOptions {// 如果编辑不过需要添加,java8,如果编辑过不需要添加
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
...
}

在setting.gradle添加:flutter_module依赖到主AndroidHost工程下

setBinding(new Binding([gradle:this]))
evaluate(new File(
        settingsDir.parentFile,
        'flutter_module/.android/include_flutter.groovy'
))
include ':flutter_module'
project(':flutter_module').projectDir = new File('../flutter_module')

编译-->成功后 在Android 项目中app的build.gradle中添加

api project(path: ':flutter')

编译

注意:Flutter库中关联的.android中的flutter的库中build.gradle的compileSdkVersion minsdkVersion以及targetSdkVersion和主项目保持一致。
Android项目中androidx和flutter项目中pub spec.yaml的androidx为true
以上已经完成了flutter到Android原生项目的依赖。

flutter内容显示到原生ui

然后 把flutter呈现到Android原生中,通过FlutterFragment加载到布局中;flutter调用原生方法,以模拟电量为例子。
原生布局:




    


/**
 * @author: George.ren
 * date: 2020/7/22 9:06 PM
 * des: flutter 放到Android 的fragment中。
 *      plugin--》plugin注册,flutter获取原生电量
 */
class MainActivity : AppCompatActivity() {
    var flutterFragment: FlutterFragment? = null

    companion object {
        val TAG = "Main-"
        val TAG_FLUTTER_FRAGMENT = "flutter_fragment"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        startFlutter()

    }

    /**
     * 显示flutter ui到 原生ui(fl_content)上
     */
    private fun startFlutter() {
        initPlugin()
        var fm = supportFragmentManager
        flutterFragment = fm.findFragmentByTag(TAG_FLUTTER_FRAGMENT) as FlutterFragment?
        if (flutterFragment == null) {
            var newFlutterFragment = FlutterFragment.withCachedEngine("my_flutter").build()
            flutterFragment = newFlutterFragment
            fm.beginTransaction().add(R.id.fl_content, flutterFragment!!, TAG_FLUTTER_FRAGMENT).commit()
            Log.d(TAG, "是否null?-->${null == flutterFragment}")
            flutterFragment!!.onAttach(applicationContext)
        }
    }

    /**
     * 初始化flutter引擎
     */
    private fun initPlugin() {
        var flutterEngine = FlutterEngine(this)
        flutterEngine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault())
        FlutterEngineCache.getInstance().put("my_flutter", flutterEngine)
        BatteryPlugin.registerWith(flutterEngine)
    }
}

flutter中的代码

import 'package:flutter/material.dart';
import 'package:flutter/services.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'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  static const platform = const MethodChannel("com.battery.io/battery");

  int _counter = 0;
  String _battery = "获取电池电量";

  Future _getBatteryLevel() async {
    String battery = "获取电池电量";
    try {
      int result = await platform.invokeMethod("getBatteryLevel");
      battery = "获取电池电量 $result";
      print("flutter-Main-$battery");
    } on PlatformException catch (e) {
      String battery = "获取电池电量 no";
      print("flutter-Main-$battery");
    }
    setState(() {
      _battery = battery;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter $_battery',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _getBatteryLevel,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

然后点击运行。

你可能感兴趣的:(Flutter 添加到现有项目(Android))