在原 Android 工程的基础上构建一个flutter工程

文章目录

在 flutter 开发的过程中不可能所有项目都是从零构建

换句话说不是所有项目都是 flutter 为主工程,然后 android/ios 的工程为副工程

大概率会遇到需要将 flutter 作为组件加入到原生项目中, 这种例子典型的就是阿里闲鱼,当然闲鱼团队的实力不是普通的小公司可以比的

所幸的是,flutter 团队提供了一个 用于帮助我们完成这个过程

创建一个 Android 工程

使用 Android Studio 创建一个新工程来模拟这个过程,会看这里的普遍都应该是 android 程序员出身,Hello World 工程是肯定会的,不会的话还是回炉加强一下吧

如果你已经有现有工程,肯定是有 VCS 管理的,放心大胆的走出第一步,大不了就删除当前分支嘛,然后你可以跳过这一步,直接看 flutter 的过程

图片

创建 Flutter

这一步仅作为 官方 Android 部分的参考

我目前使用的是 1.0.0 的发布版

1Flutter 1.0.0 • channel dev • https://github.com/flutter/flutter.git
2Framework • revision 5391447fae (11 days ago) • 2018-11-29 19:41:26 -0800
3Engine • revision 7375a0f414
4Tools • Dart 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

wiki 后续可能会被修改,请查看最新的文档去解决

这里要注意,你要在和你现有的 Application 同级的目录来使用

比如你的 Application

 1➜  ExistsApp flutter create -t module my_flutter
 2Creating project my_flutter...
 3  my_flutter/.gitignore (created)
 4  my_flutter/.idea/libraries/Dart_SDK.xml (created)
 5  my_flutter/.idea/libraries/Flutter_for_Android.xml (created)
 6  my_flutter/.idea/modules.xml (created)
 7  my_flutter/.idea/workspace.xml (created)
 8  my_flutter/.metadata (created)
 9  my_flutter/lib/main.dart (created)
10  my_flutter/my_flutter.iml (created)
11  my_flutter/my_flutter_android.iml (created)
12  my_flutter/pubspec.yaml (created)
13  my_flutter/README.md (created)
14  my_flutter/test/widget_test.dart (created)
15Running "flutter packages get" in my_flutter...              7.5s
16Wrote 12 files.
17
18All done!
19Your module code is in my_flutter/lib/main.dart.

这里 flutter 工程就创建成功了

打包 aar 文件/修改 host application

这一步是构建一个 aar 文件

1cd .android/
2./gradlew flutter:assembleDebug

20190121173003.png

接着修改 setting.gradle 文件

1include ':app'                                     // assumed existing content
2setBinding(new Binding([gradle: this]))                                 // new
3evaluate(new File(                                                      // new
4  settingsDir.parentFile,                                               // new
5  'my_flutter/.android/include_flutter.groovy'                          // new
6))

20190121172743.png

sync 以后 如果有 flutter 说明关联到项目中了

20190121173354.png

接着,将 flutter 设置为 android 的库

加入这个,然后继续同步一下

1dependencies {
2  implementation project(':flutter')
3}

20190121173713.png

能看见的话就说明加入成功了

20190121173657.png

修改 android 工程

activity_main.xml

 1<?xml version="1.0" encoding="utf-8"?>
 2<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3    xmlns:app="http://schemas.android.com/apk/res-auto"
 4    xmlns:tools="http://schemas.android.com/tools"
 5    android:layout_width="match_parent"
 6    android:layout_height="match_parent"
 7    tools:context=".MainActivity">
 8
 9    <TextView
10        android:id="@+id/tv_text"
11        android:layout_width="wrap_content"
12        android:layout_height="wrap_content"
13        android:text="Hello World!"
14        app:layout_constraintBottom_toBottomOf="parent"
15        app:layout_constraintLeft_toLeftOf="parent"
16        app:layout_constraintRight_toRightOf="parent"
17        app:layout_constraintTop_toTopOf="parent" />
18
19    <Button
20        android:id="@+id/bt_to_flutter"
21        android:layout_width="wrap_content"
22        android:layout_height="wrap_content"
23        android:layout_marginTop="8dp"
24        android:text="to Flutter page"
25        app:layout_constraintLeft_toLeftOf="parent"
26        app:layout_constraintRight_toRightOf="parent"
27        app:layout_constraintTop_toBottomOf="@id/tv_text" />
28
29</android.support.constraint.ConstraintLayout>

MainActivity.java

 1package top.kikt.addexiststoandroid;
 2
 3import android.content.Intent;
 4import android.os.Bundle;
 5import android.support.v7.app.AppCompatActivity;
 6import android.view.View;
 7
 8public class MainActivity extends AppCompatActivity {
 9
10    @Override
11    protected void onCreate(Bundle savedInstanceState) {
12        super.onCreate(savedInstanceState);
13        setContentView(R.layout.activity_main);
14
15        findViewById(R.id.bt_to_flutter).setOnClickListener(new View.OnClickListener() {
16            @Override
17            public void onClick(View v) {
18                // to flutter activity
19                Intent intent = new Intent(MainActivity.this, MyFlutterActivity.class);
20                startActivity(intent);
21            }
22        });
23    }
24}

MyFlutterActivity.java

 1package top.kikt.addexiststoandroid;
 2
 3import android.os.Bundle;
 4import android.support.v4.app.FragmentActivity;
 5import android.widget.FrameLayout;
 6
 7import io.flutter.facade.Flutter;
 8import io.flutter.view.FlutterView;
 9
10/// create 2019/1/22 by cai
11
12
13public class MyFlutterActivity extends FragmentActivity {
14
15    @Override
16    protected void onCreate(Bundle savedInstanceState) {
17        super.onCreate(savedInstanceState);
18        FlutterView flutterView = Flutter.createView(this, getLifecycle(), "route1");
19        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
20        addContentView(flutterView, params);
21    }
22
23}

别忘了增加 Activity 的清单文件

1 <activity android:name=".MyFlutterActivity" />

修改 flutter 工程

main.dart

  1import 'package:flutter/material.dart';
  2import 'dart:ui' as ui;
  3
  4void main() {
  5  var routeName = ui.window.defaultRouteName;
  6
  7  switch (routeName) {
  8    case "route1":
  9      runApp(MyApp());
 10      break;
 11    default:
 12      runApp(EmptyWidget());
 13  }
 14}
 15
 16class EmptyWidget extends StatelessWidget {
 17  @override
 18  Widget build(BuildContext context) {
 19    return MaterialApp(
 20      home: Scaffold(
 21        body: Center(
 22          child: Container(
 23            child: Text("空路由"),
 24          ),
 25        ),
 26      ),
 27    );
 28  }
 29}
 30
 31class MyApp extends StatelessWidget {
 32  // This widget is the root of your application.
 33  @override
 34  Widget build(BuildContext context) {
 35    return MaterialApp(
 36      title: 'Flutter Demo',
 37      theme: ThemeData(
 38        // This is the theme of your application.
 39        //
 40        // Try running your application with "flutter run". You'll see the
 41        // application has a blue toolbar. Then, without quitting the app, try
 42        // changing the primarySwatch below to Colors.green and then invoke
 43        // "hot reload" (press "r" in the console where you ran "flutter run",
 44        // or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the
 45        // counter didn't reset back to zero; the application is not restarted.
 46        primarySwatch: Colors.blue,
 47      ),
 48      home: MyHomePage(title: 'Flutter Demo Home Page'),
 49    );
 50  }
 51}
 52
 53class MyHomePage extends StatefulWidget {
 54  MyHomePage({Key key, this.title}) : super(key: key);
 55
 56  // This widget is the home page of your application. It is stateful, meaning
 57  // that it has a State object (defined below) that contains fields that affect
 58  // how it looks.
 59
 60  // This class is the configuration for the state. It holds the values (in this
 61  // case the title) provided by the parent (in this case the App widget) and
 62  // used by the build method of the State. Fields in a Widget subclass are
 63  // always marked "final".
 64
 65  final String title;
 66
 67  @override
 68  _MyHomePageState createState() => _MyHomePageState();
 69}
 70
 71class _MyHomePageState extends State<MyHomePage> {
 72  int _counter = 0;
 73
 74  void _incrementCounter() {
 75    setState(() {
 76      // This call to setState tells the Flutter framework that something has
 77      // changed in this State, which causes it to rerun the build method below
 78      // so that the display can reflect the updated values. If we changed
 79      // _counter without calling setState(), then the build method would not be
 80      // called again, and so nothing would appear to happen.
 81      _counter++;
 82    });
 83  }
 84
 85  @override
 86  Widget build(BuildContext context) {
 87    // This method is rerun every time setState is called, for instance as done
 88    // by the _incrementCounter method above.
 89    //
 90    // The Flutter framework has been optimized to make rerunning build methods
 91    // fast, so that you can just rebuild anything that needs updating rather
 92    // than having to individually change instances of widgets.
 93    return Scaffold(
 94      appBar: AppBar(
 95        // Here we take the value from the MyHomePage object that was created by
 96        // the App.build method, and use it to set our appbar title.
 97        title: Text(widget.title),
 98      ),
 99      body: Center(
100        // Center is a layout widget. It takes a single child and positions it
101        // in the middle of the parent.
102        child: Column(
103          // Column is also layout widget. It takes a list of children and
104          // arranges them vertically. By default, it sizes itself to fit its
105          // children horizontally, and tries to be as tall as its parent.
106          //
107          // Invoke "debug painting" (press "p" in the console, choose the
108          // "Toggle Debug Paint" action from the Flutter Inspector in Android
109          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
110          // to see the wireframe for each widget.
111          //
112          // Column has various properties to control how it sizes itself and
113          // how it positions its children. Here we use mainAxisAlignment to
114          // center the children vertically; the main axis here is the vertical
115          // axis because Columns are vertical (the cross axis would be
116          // horizontal).
117          mainAxisAlignment: MainAxisAlignment.center,
118          children: <Widget>[
119            Text(
120              'You have pushed the button this many times:',
121            ),
122            Text(
123              '$_counter',
124              style: Theme.of(context).textTheme.display1,
125            ),
126          ],
127        ),
128      ),
129      floatingActionButton: FloatingActionButton(
130        onPressed: _incrementCounter,
131        tooltip: 'Increment',
132        child: Icon(Icons.add),
133      ), // This trailing comma makes auto-formatting nicer for build methods.
134    );
135  }
136}

运行

运行 flutter 工程

这里要注意,我这里在 flutter 下直接运行会得到下面的结果, 所以你需要自己在 debug 的情况下指定一个路由

修改 main.dart 中的 main 方法为如下结果

 1void main() {
 2  var routeName = ui.window.defaultRouteName;
 3  routeName = "route1"; // 新增这一行
 4  switch (routeName) {
 5    case "route1":
 6      runApp(MyApp());
 7      break;
 8    default:
 9      runApp(EmptyWidget());
10  }
11}

正式运行的时候一定要注释掉,如果不注释掉, 原生工程中的那个 route1 就失效了

然后运行下

img

看起来和默认的 hello world 工程是一样的

运行原生工程

为什么看起来是一样的呢,flutter run 默认运行的是当前目录下的 lib/main.dart, 然后找 main 方法, main 方法中就是 runApp,所以看起来就是这样的了

但我们需要的是将 flutter 加入到原生工程中去,那么我们就需要在原生工程里面去运行这个项目

我们直接在 android studio 中运行项目,可能会得到下面的结果,也可能没有 这个应该和你 android 中的 min sdk /target sdk 版本有关系,有原生经验的人

20190122085942.png

拿着错误信息随手一百度能看到一个

20190122094535.png

ok 我们在 android 项目中加入这个, 这个意思就是指定 java 的版本为 1.8(java 8)

修改 gradle 文件

app 下的 build.gradle

1android{
2    compileOptions {
3        sourceCompatibility JavaVersion.VERSION_1_8
4        targetCompatibility JavaVersion.VERSION_1_8
5    }
6}

接着就可以跑起来项目了

img

点击按钮

i

微调一下

我们看到 flutter 界面上会比较怪, 这是因为原生和 flutter 主题色不一样的原因

修改原生的主题色 colors.xml

1<?xml version="1.0" encoding="utf-8"?>
2<resources>
3    <color name="colorPrimary">#2196F3</color>
4    <color name="colorPrimaryDark">#19639e</color>
5    <color name="colorAccent">#D81B60</color>
6</resources>

再打开原生项目可以看到颜色发生了变化

img

后记

简单的添加 flutter 到 android 就完成了,当然在具体实施中还会有很多问题,只能在具体情况具体分析了

如果遇到问题,欢迎在后面留言

另外,如果遇到了本篇和 wiki 不同的情况,请以 wiki 为准,毕竟官方 wiki 的更新会比较频繁,就在我写这篇文章的时候,还在间隔几天更新一次