# Technical Documentation: alibaba/flutter_boost

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/alibaba/flutter_boost)

### Overview (README.md)

<p align="center">
  <img src="flutter_boost.png">
   <b></b><br>
  <a href="README_CN.md">中文文档</a>
  <a href="https://zhuanlan.zhihu.com/p/362662962">中文介绍</a>
</p>

# Release Note

## [ohos] New Platform
flutter_boost has been fully adapted for the ohos platform. Please refer to item 10 of the following document to understand the related conventions before integrating：
<a href="Frequently Asked Question.md">FAQ</a>

## 4.6.5

PS：Null-safety is already supported.

- Flutter SDK upgrades do not require Boost upgrades
- Simplify the architecture
- Simplify the interface
- Unified design of double-end interface
- Solved the Top Issue
- Android does not need to distinguish between AndroidX and Support

# FlutterBoost
A next-generation Flutter-Native hybrid solution. FlutterBoost is a Flutter plugin which enables hybrid integration of Flutter for your existing native apps with minimum efforts. The philosophy of FlutterBoost is to use Flutter as easy as using a WebView. Managing Native pages and Flutter pages at the same time is non-trivial in an existing App. FlutterBoost takes care of page resolution for you. The only thing you need to care about is the name of the page(usually could be an URL). 
<a name="bf647454"></a>

# Prerequisites

1. Before proceeding, you need to integrate Flutter into your existing project.
2. The Flutter SDK version supported by Boost 3.0 is >= 1.22


# Getting Started


## Add a dependency in you Flutter project.

Open you pubspec.yaml and add the following line to dependencies:

``` yaml
flutter_boost:
    git:
        url: 'https://github.com/alibaba/flutter_boost.git'
        ref: '4.6.5'
```

# Version Notes
- For Flutter SDK 3.0 and above, use `4.0.1+`.
- For Flutter SDK below 3.0, use `v3.0-release.2` or earlier versions.
- The null safety versions supporting Flutter SDK 2.5.x are `3.1.0+`.
- The versions supporting Flutter SDK 3.16.x are `5.0.0+`.
- The versions supporting HarmonyOS are `[4.5.0, 5.0.0)`.


# Usage
- [Detailed Integration Steps](https://github.com/alibaba/flutter_boost/blob/master/docs/install.md)
- [Basic Routing API](https://github.com/alibaba/flutter_boost/blob/master/docs/routeAPI.md)
- [API for Page Lifecycle](https://github.com/alibaba/flutter_boost/blob/master/docs/lifecycle.md)
- [Custom API for Sending Cross-Platform Events](https://github.com/alibaba/flutter_boost/blob/master/docs/event.md)

# Contribution
- [How to File an Issue to Us](https://github.com/alibaba/flutter_boost/blob/master/docs/issue.md)
- [How to Submit a PR to Us](https://github.com/alibaba/flutter_boost/blob/master/docs/pr.md)

# FAQ
please read this document:
<a href="Frequently Asked Question.md">FAQ</a>


# License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details

## About Us
Alibaba-Xianyu Tech is one of the earliest and largest teams running Flutter on a large scale online in China.

In our official WeChat account, we have carefully selected exclusive Flutter content for you, both comprehensive and in-depth.

The content includes tutorials and open-source information on Flutter integration, large-scale applications, engine exploration, engineering systems, and innovative technologies.

**Architects / Backend Engineers / Client-side Engineers / Frontend Developers / Algorithm Engineers / Quality Engineers - submit your resumes through our WeChat account, there is no limit to the number of positions.**

We welcome you to join Xianyu and become a curious, happy, and influential programmer. To send your resume, please email: `tino.wjf@alibaba-inc.com`

Subscribe at:

<img src="https://img.alicdn.com/tfs/TB17Ki5XubviK0jSZFNXXaApXXa-656-656.png" width="328px" height="328px">

[For English](https://twitter.com/xianyutech "For English")

---

### Doc Api Static Assets Readme (`doc/api/static-assets/readme.md`)

# highlight.js

Generated from https://highlightjs.org/download/ on 2021-07-13

**Included languages:**

* bash
* c  
* css
* dart
* diff
* html, xml
* java
* javascript
* json
* kotlin
* markdown
* objective-c
* plaintext  
* shell
* swift
* yaml

---

### Event (`docs/event.md`)

# 自定义事件传递API

这个部分相当于让开发者省略了手动搭桥的功能，通过事件标识key和参数map即可完成事件传递


## flutter端使用

 - 接收消息
```dart
///声明一个用来存回调的对象
VoidCallback removeListener;

///添加事件响应者,监听native发往flutter端的事件
removeListener = BoostChannel.instance.addEventListener("yourEventKey", (key, arguments) {
  ///deal with your event here
  return;
});

///然后在退出的时候（比如dispose中）移除监听者
removeListener?.call();
```

 - 发送消息给native
```dart
BoostChannel.instance.sendEventToNative("eventToNative",{"key1":"value1"});
```

## iOS端使用

 - 接收消息
```swift
//同样声明一个对象用来存删除的函数
var removeListener:FBVoidCallback?

//这里注册事件监听，监听flutter发送到iOS的事件
self.removeListener =  FlutterBoost.instance().addEventListener({[weak self] key, dic in
    //注意，如果这里self持有removeListener，而这个闭包中又有self的话，要用weak self
    //否则就有self->removeListener->self 循环引用
    
    //在这里处理你的事件
    
}, forName: "event")

//在退出的时候解除注册(比如 deinit/dealloc 中)
removeListener?()
```

- 发送消息给flutter
```swift
FlutterBoost.instance().sendEventToFlutter(with: "event", arguments: ["data":"event from native"])
```

## Android端使用

 - 接收消息

```java
EventListener listener = (key, args) -> {
    //deal with your event here      
};
ListenerRemover remover = FlutterBoost.instance().addEventListener("event", listener);

//最后在清理的时候移除监听(比如onDestroy中)
remover.remove();
```

- 发送消息给flutter
```java
Map<Object,Object> map = new HashMap<>();
map.put("key","value");
FlutterBoost.instance().sendEventToFlutter("eventToFlutter",map);
```

---

### Install (`docs/install.md`)

# 各平台安装

## 1. 目录结构

我们新建一个文件夹FlutterBoostExample，这个文件夹下面放置另外三个文件夹。 另外三个分别是您的Android工程，iOS工程，以及需要接入的flutter module，
这个地方注意，flutter一定是module，而不是工程项目，判断是不是module的方法就是看其是否有android和ios文件夹， 如果没有，那就是module，才是正确的

在这里我们命名为`BoostTestAndroid`，`BoostTestIOS`,以及`flutter_module`
注意：这三个工程在同级目录下

现在可以开始搞事情了

## Dart部分

1. 首先，需要添加`FlutterBoost`依赖到`yaml`文件

```yaml
flutter_boost:
  git:
    url: 'https://github.com/alibaba/flutter_boost.git'
    ref: '4.6.5'
```

之后在flutter工程下运行`flutter pub get` dart端就集成完毕了，然后可以在dart端放上一些代码,以下代码基于example3.0

//这里要特别注意，如果你的工程里已经有一个继承自`WidgetsFlutterBinding`的自定义Binding，则只需要将其with上`BoostFlutterBinding`
//如果你的工程没有自定义的Binding，则可以参考这个`CustomFlutterBinding`的做法 //`BoostFlutterBinding`用于接管Flutter App的生命周期，必须得接入的

```
/* Detailed source-code truncated for AI context efficiency. */
```

到此dart端就集成完毕了

## Android部分

1. 在setting.gradle文件中添加如下的代码,这一步是引用flutter工程 添加之后`Binding`会报红，这个地方不管他，直接往下看

```
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')
```

2. 然后在app的build.gradle下添加如下代码

```
implementation project(':flutter')
implementation project(':flutter_boost')
```

3. 还需要在清单文件中添加以下内容直接粘贴到`<application>`标签包裹的内部即可，也就是和其他`<activity>`标签同级

```xml
<activity
        android:name="com.idlefish.flutterboost.containers.FlutterBoostActivity"
        android:theme="@style/Theme.AppCompat"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize" >

</activity>
<meta-data android:name="flutterEmbedding"
           android:value="2">
</meta-data>


```

然后点击右上角的sync同步一下，就会开始一些下载和同步的进程，等待完成

4. 在`Application`中添加`FlutterBoost`的启动流程，并设置代理

```java
public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        FlutterBoost.instance().setup(this, new FlutterBoostDelegate() {
            @Override
            public void pushNativeRoute(FlutterBoostRouteOptions options) {
                //这里根据options.pageName来判断你想跳转哪个页面，这里简单给一个
                Intent intent = new Intent(FlutterBoost.instance().currentActivity(), YourTargetAcitvity.class);
                FlutterBoost.instance().currentActivity().startActivityForResult(intent, options.requestCode());
            }

            @Override
            public void pushFlutterRoute(FlutterBoostRouteOptions options) {
                Intent intent = new FlutterBoostActivity.CachedEngineIntentBuilder(FlutterBoostActivity.class)
                        .backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent)
                        .destroyEngineWithActivity(false)
                        .uniqueId(options.uniqueId())
                        .url(options.pageName())
                        .urlParams(options.arguments())
                        .build(FlutterBoost.instance().currentActivity());
                FlutterBoost.instance().currentActivity().startActivity(intent);
            }
        }, engine -> {
        });
    }
}
```

到此为止Android的集成流程就全部完成

## iOS部分

1. 首先到自己的iOS目录下，执行`pod init`,之后执行一次`pod install`

2. 打开创建的Podfile文件，添加以下代码

```
flutter_application_path = '../flutter_module'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
install_all_flutter_pods(flutter_application_path)
```

添加之后，您的Podfile应该类似下面这样

```
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

flutter_application_path = '../flutter_module'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')

target 'BoostTestIOS' do
  use_frameworks!

  install_all_flutter_pods(flutter_application_path)

end
```

然后再执行`pod install`,安装完成

3.进行准备工作创建`FlutterBoostDelegate`。 这里面的内容是完全可以自定义的，在您了解各个API的含义时，你可以完全自定义这里面每个方法的代码，下面只是给出大多数场景的默认解法

```
/* Detailed source-code truncated for AI context efficiency. */
```

4.在`AppDelegate`的`didFinishLaunchingWithOptions`方法中进行初始化

```swift
//创建代理，做初始化操作
let delegate = BoostDelegate()
FlutterBoost.instance().setup(application, delegate: delegate) { engine in

}
```

## OHOS部分

单UIAbility

整个应用只有唯一UIAbility，Flutter界面由FlutterPage进行承载

1. Flutter与UIAbility进行绑定

在UIAbility的`onCreate`，`onDestroy`，`onWindowStageCreate`，`onWindowStageDestroy`生命周期函数将Flutter进行绑定。

```typescript
async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
  FlutterManager.getInstance().pushUIAbility(this)：
}

onDestroy(): void {
  FlutterManager.getInstance().popUIAbility(this);
}

onWindowStageCreate(windowStage: window.WindowStage): void {
  FlutterManager.getInstance().pushWindowStage(this, windowStage)
}

onWindowStageDestroy(): void {
  FlutterManager.getInstance().popWindowStage(this);
}
```

1. 初始化FlutterBoost

因为FlutterBoost调用usetup后会初始化引擎，建议的初始化optionsBuilder时带上GeneratedPluginRegistrant.getPlugins()

- 当前UIAbility继承FlutterBoostDelegate
- 并在适当的时机调用`FlutterBoost.getInstance().setup` (建议onWindowStageCreate)

```typescript
export default class EntryAbility extends UIAbility implements FlutterBoostDelegate {
  // FlutterBoostDelegate override
  pushNativeRoute(options: FlutterBoostRouteOptions) {

  }
  // FlutterBoostDelegate override
  pushFlutterRoute(options: FlutterBoostRouteOptions) {

    router.pushUrl({
      url: 'pages/MyFlutterPage', params: {
        uri: options.getPageName(),
        params: options.getArguments(),
      }
    }).then(() => {
      console.info('Succeeded in jumping to the second page.')
    })
  }
  onWindowStageCreate(windowStage: window.WindowStage): void {

    // 初始化启动参数（建议带上GeneratedPluginRegistrant.getPlugins()）
    const optionsBuilder: FlutterBoostSetupOptionsBuilder = new FlutterBoostSetupOptionsBuilder()
      .setPlugins(GeneratedPluginRegistrant.getPlugins());

    FlutterBoost.getInstance().setup(this, this.context, () => {
      //引擎初始化成功
    }, optionsBuilder.build())

  }
}
```
如果想要带Promise的setup函数，请使用`FlutterBoost.getInstance().setupSync`

1. 自定义FlutterPage

创建一个Page，加上相关相关`FlutterBoostEntry`以及`FlutterPage`代码

```typescript
@Entry
@Component
struct MyFlutterPage {
  private flutterEntry: FlutterBoostEntry | null = null;
  private flutterView?: FlutterView

  aboutToAppear() {
    this.flutterEntry = new FlutterBoostEntry(getContext(this), router.getParams());
    this.flutterEntry.aboutToAppear();
    this.flutterView = this.flutterEntry.getFlutterView();
    hilog.info(0x0000, "Flutter", "Index aboutToAppear===");
  }
  //2
  aboutToDisappear() {
    hilog.info(0x0000, "Flutter", "Index aboutToDisappear===");
    this.flutterEntry?.aboutToDisappear()
  }

  onPageShow() {
    hilog.info(0x0000, "Flutter", "Index onPageShow===");
    this.flutterEntry?.onPageShow()
  }
  // 1
  onPageHide() {
    hilog.info(0x0000, "Flutter", "Index onPageHide===");
    this.flutterEntry?.onPageHide()
  }

  build() {
    Stack() {
      FlutterPage({ viewId: this.flutterView?.getId() })
    }
  }

  // 拦截返回键
  onBackPress(): boolean | void {
    FlutterBoost.getInstance().getPlugin()?.onBackPressed();
    return true;
  }
}
```

4. 跳转Flutter界面
   后面直接使用router跳转到3步骤中的page即可
```typescript

router.pushUrl({
  url: 'pages/MyFlutterPage', params: {
    uri: '这里写dart侧注册好的路由名',
    params: '传递给界面的参数',
  }
}).then(() => {
  console.info('Succeeded in jumping to the second page.')
})
```

*多tab共存*

如何在多tab上有多个flutter界面共存。

```
/* Detailed source-code truncated for AI context efficiency. */
```



到此为止，所有的前置内容均已完成

---

### Issue (`docs/issue.md`)

# 如何向我们提issue

1. 在issue里面用语言简单描述一下您的场景以及出现的bug


2. 之后您可以fork一个分支，然后在您的分支上，在`example3.0`中添加一个您用于
   复现bug场景的用例入口
   - 如果您的入口是原生端，在原生的页面上加按钮添加操作即可。
   - 如果您的入口是flutter端，那就在flutter的`main_page`列表中添加一个Model即可添加用例，具体可以查看代码

**<font color='red'> 注意，这个地方不支持使用其他方式提交复现代码（原因在于，如果大家使用自己的代码，容易带有使用的错误以及自己的业务逻辑，
   我们就不清楚是业务问题还是框架本身的问题，之前遇到了一些同学，debug下来结果是自己业务代码出了问题造成结果不一致，所以请理解） </font>**

3. 在您的issue中给出您的分支链接，提交即可，我们debug的时候就会直接进入您分支下的`exmaple3.0`中您所给的用例进行bug复现

---

### Lifecycle (`docs/lifecycle.md`)

# 生命周期API部分（这部分只有flutter端，无原生实现）

## 1. 全局监听API

一般在main阶段就可以添加一个全局观察者
```dart
void main() {
  ///添加全局生命周期监听类
  PageVisibilityBinding.instance.addGlobalObserver(AppLifecycleObserver());
  runApp(MyApp());
}
```

`AppLifecycleObserver`的具体实现如下
```dart
///全局生命周期监听示例
class AppLifecycleObserver with GlobalPageVisibilityObserver {
  @override
  void onBackground(Route route) {
    super.onBackground(route);
    print("AppLifecycleObserver - onBackground");
  }

  @override
  void onForeground(Route route) {
    super.onForeground(route);
    print("AppLifecycleObserver - onForground");
  }

  @override
  void onPagePush(Route route) {
    super.onPagePush(route);
    print("AppLifecycleObserver - onPagePush");
  }

  @override
  void onPagePop(Route route) {
    super.onPagePop(route);
    print("AppLifecycleObserver - onPagePop");
  }

  @override
  void onPageHide(Route route) {
    super.onPageHide(route);
    print("AppLifecycleObserver - onPageHide");
  }

  @override
  void onPageShow(Route route) {
    super.onPageShow(route);
    print("AppLifecycleObserver - onPageShow");
  }
}
```

## 2.单个页面的监听
```dart
///单个生命周期示例
class LifecycleTestPage extends StatefulWidget {
  const LifecycleTestPage({Key key}) : super(key: key);

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

class _LifecycleTestPageState extends State<LifecycleTestPage>
    with PageVisibilityObserver {
  @override
  void onBackground() {
    super.onBackground();
    print("LifecycleTestPage - onBackground");
  }

  @override
  void onForeground() {
    super.onForeground();
    print("LifecycleTestPage - onForeground");
  }

  @override
  void onPageHide() {
    super.onPageHide();
    print("LifecycleTestPage - onPageHide");
  }

  @override
  void onPageShow() {
    super.onPageShow();
    print("LifecycleTestPage - onPageShow");
  }

  @override
  void initState() {
    super.initState();

    ///请在didChangeDependencies中注册而不是initState中
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    ///注册监听器
    PageVisibilityBinding.instance.addObserver(this, ModalRoute.of(context));
  }

  @override
  void dispose() {
    ///移除监听器
    PageVisibilityBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ...;
  }
}
```

### 额外说明
 - 在页面层级，没有`push`事件和`pop`事件，初始化逻辑请直接写在`initState`，卸载逻辑请写在`dispose`中即可

 - `onPageShow`对标Android`onResume`，iOS `viewDidAppear`
 - `onPageHide`对标Android`onStop`，iOS `viewDidDisappear`

---

### Pr (`docs/pr.md`)

# Pull Requset流程

1. 提一个issue，标题前标注`[featurePR]`描述一下您的使用场景，以及boost框架为何不能满足您所述的场景
   标题例子如下：
```
[featurePR]使FlutterBoost支持xxxxx功能
```
然后在issue的描述部分简述您解决该问题的思路即可

2. 我们在收到您的issue后会对您的feature以及您的方案进行评估，如果评估结果成功，您将进入流程3，否则流程结束
   
3. 您可以为PR开始coding了，提交时，您除了提交您的修改代码之外，还需要:
   - 在`exmaple3.0`中添加/修改相关用例，**如果原代码中不支持您的用例，那么您可以自行添加/修改用例用例以支持您PR的场景**
   - 在`AUTHORS`文件中添加您的名字和邮箱，具体可自行查看书写格式，表明您对我们的框架做过贡献的记录，如果已存在您的信息，就不用添加了

4. 在PR中写上明确的标题和描述，描述中写上您PR的这个用例的复现路径(基于`exmaple3.0`)
  
**<font color='red'> 提交的主代码和 格式化操作 请分开提交，不然review起来是比较麻烦的 </font>**


5. 提交PR，等待回应即可

---

### RouteAPI (`docs/routeAPI.md`)

# 基本路由API部分

## Dart 部分
### 1.开启新页面统一API
```dart
BoostNavigator.instance.push(
    "yourPage", //required
    withContainer: false, //optional
    arguments: {"key":"value"}, //optional
    opaque: true, //optional,default value is true
);

///or

Navigator.of(context).pushNamed('simplePage', arguments: {'data': _controller.text});

///不能使用匿名路由，boost目前无法捕捉匿名路由，匿名路由就是直接使用类似
///类似CupertinoPageRoute的形式来进行push，暂不支持！！！
```

参数名 | 意义 | 是否可选
-------- | -----| -----
`name` | 页面在路由表中的名字 | NO
`withContainer` | 是否需伴随原生容器弹出 | YES
`arguments` | 携带到下一页面的参数 | YES
`opaque` | 页面是否透明(下面会再次提到) | YES

### 2.开启透明弹窗(flutter中开启弹窗)

- 不开启新容器的flutter内部弹窗(推荐)

```dart
///首先你需要在你的routeFactory路由表中这样指定弹窗页面
'dialogPage': (settings, uniqueId) {
    return PageRouteBuilder<dynamic>(

      ///透明弹窗页面这个需要是false
      opaque: false,

      ///背景蒙版颜色
      barrierColor: Colors.black12,
      settings: settings,
      pageBuilder: (_, __, ___) => DialogPage());
},

///然后这样弹出即可
BoostNavigator.instance.push("dialogPage");

///如果要接收参数返回参数的形式
final result = await BoostNavigator.instance.push("dialogPage");
```


- 开启新容器的flutter内部弹窗

dialogPage在路由表中的注册方法可以同上
```dart
 BoostNavigator.instance.push("dialogPage",
        withContainer: true,

        ///如果开启新容器，需要指定opaque为false
        opaque: false);
```


### 3.关闭页面API
```dart
///pop一次
BoostNavigator.instance.pop(result);

///pop两次,首次需要用await等待
await BoostNavigator.instance.pop(result);
BoostNavigator.instance.pop(result);
```

参数名 | 意义 | 是否可选
-------- | -----| -----
`result` | 返回的参数 | YES
 - ##### 一定注意：如果打开的Flutter页面不带容器（例如，通过原生的Navigator.push，或者withContainer=false），那么pop时，result可以是任何类型；如果打开的页面是一个带容器的Flutter页面（即，withContainer=true）或一个Native页面，那么result需要是`Map<String, dynamic>`类型。



## Android
### 1.开启新页面统一API
```java
FlutterBoostRouteOptions options = new FlutterBoostRouteOptions.Builder()
                .pageName("pageName")
                .arguments(new HashMap<>())
                .requestCode(1111)
                .build();
FlutterBoost.instance().open(options);
```


### 2.关闭页面API（用得比较少）
```java
FlutterBoost.instance().close(uniqueId);
```


### 3.页面关闭时，返回结果给前一个页面
#### 3.1 Flutter页面退出时，传递参数给上一个Native页面

FlutterBoostActivity示例如下：
```java
// 1. 打开Flutter页面，等待返回结果
Intent intent = new FlutterBoostActivity.CachedEngineIntentBuilder(FlutterBoostActivity.class)
        .backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.opaque)
        .destroyEngineWithActivity(false)
        .url("DialogPage")
        .urlParams(params)
        .build(this);
startActivityForResult(intent, REQUEST_CODE);

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // 处理返回结果
}
```

```dart
// 2. 关闭Flutter页面，返回结果
InkWell(
child: Container(
    padding: const EdgeInsets.all(8.0),
    margin: const EdgeInsets.all(8.0),
    color: Colors.yellow,
    child: Text(
        'Pop with Navigator',
        style: TextStyle(fontSize: 22.0, color: Colors.blue),
    )),
// 这里也可以使用: Navigator.of(context).pop({'retval' : 'I am from dart...'})
onTap: () => BoostNavigator.instance.pop({'retval' : 'I am from dart...'}),
),
```

注：如需定制，请自行实现FlutterViewContainer的finishContainer接口。

#### 3.2 Native页面退出时，传递参数给上一个Flutter页面

```dart
// 1. 从Flutter页面打开一个Native页面，并处理返回结果
InkWell(
child: Container(
    padding: const EdgeInsets.all(8.0),
    margin: const EdgeInsets.all(8.0),
    color: Colors.yellow,
    child: Text(
        'open native page',
        style: TextStyle(fontSize: 22.0, color: Colors.black),
    )),
onTap: () => BoostNavigator.instance
    .push("ANativePage") // Native页面路由
    .then((value) => print('retval:$value')),
),
```

```java
// 2. Native页面退出时，返回结果
@Override
public void finish() {
    Intent intent = new Intent();
    intent.putExtra("msg","This message is from Native!!!");
    intent.putExtra("bool", true);
    intent.putExtra("int", 666);
    setResult(Activity.RESULT_OK, intent);  // 返回结果给dart
    super.finish();
}
```

#### 3.3 Flutter页面退出时，传递参数给上一个Flutter页面
```dart
// 1. 打开一个Flutter页面，并处理返回结果
InkWell(
child: Container(
    padding: const EdgeInsets.all(8.0),
    margin: const EdgeInsets.all(8.0),
    color: Colors.yellow,
    child: Text(
        'open transparent widget',
        style: TextStyle(fontSize: 22.0, color: Colors.black),
    )),
onTap: () {
    // 如果withContainer为false时，也可以使用原生的Navigator
    final result = await BoostNavigator.instance.push("AFlutterPage",
        withContainer: true, opaque: false);
},
),

// 2. 页面关闭，并返回结果
// 这里也可以使用原生的 Navigator
onTap: () => BoostNavigator.instance.pop({'retval' : 'I am from dart...'}),
```

## iOS

### 1.开启新页面统一API

```swift
let options = FlutterBoostRouteOptions()
options.pageName = "mainPage"
options.arguments = ["key" :"value"]

//页面是否透明（用于透明弹窗场景），若不设置，默认情况下为true
options.opaque = true

//这个是push操作完成的回调，而不是页面关闭的回调！！！！
options.completion = { completion in
    print("open operation is completed")
}

//这个是页面关闭并且返回数据的回调，回调实际需要根据您的Delegate中的popRoute来调用
options.onPageFinished = { dic in
    print(dic)
}

FlutterBoost.instance().open(options)
```

### 2.关闭页面API（用得比较少）
```swift
FlutterBoost.instance().close(uniqueId)
```

### 3.原生参数回传flutter
```swift
//这里pageName是你push的这个原生的pageName，而不是上一个flutter页面的pageName
//这句话并不会退出页面
FlutterBoost.instance().sendResultToFlutter(withPageName: "pageName", arguments: ["key":"value"])
```

### 下一步：[生命周期API](https://github.com/alibaba/flutter_boost/blob/master/docs/lifecycle.md)

---

--- METRICS ---
- Files Extracted: 8
- Estimated Token Budget: ~5583 tokens
- Canonical Reference: https://codewiki.google/github.com/alibaba/flutter_boost
