Overview
In the previous chapter, we introduced how to initialize the Flutter engine. This article focuses on how to add and jump to the Flutter page.
Jump Principle
The jump principle is as follows:
Essentially, it jumps from a native page A to another native page B, but the difference is that page B is a page container with embedded Flutter content.
At the same time, before opening page B, we need to notify Flutter to switch pages in advance. Here, the communication mechanism provided by Flutter is used, that is, EventChannel.
Add FlutterPage
In order to display Flutter content, we need to create a native page as a container to host Flutter.
Add a page in the entry/src/main/etc/pages
directory, for example, name it FlutterContainerPage
, right-click the ohos/entry/src/main/ets/pages
directory, select New->Page->Empty Page, change PageName to FlutterContainerPage
, click Finish, and then modify the page content as follows:
import { FlutterEntry, FlutterPage, FlutterView } from '@ohos/flutter_ohos'
@Entry
@Component
struct Index {
private flutterEntry?: FlutterEntry;
private flutterView?: FlutterView;
aboutToAppear() {
this.flutterEntry = new FlutterEntry(getContext(this));
this.flutterEntry.aboutToAppear();
this.flutterView = this.flutterEntry.getFlutterView();
}
aboutToDisappear() {
this.flutterEntry?.aboutToDisappear();
}
onPageShow() {
this.flutterEntry?.onPageShow();
}
onPageHide() {
this.flutterEntry?.onPageHide();
}
build() {
RelativeContainer() {
FlutterPage({ viewId: this.flutterView?.getId()})
}
}
}
FlutterPage is a component provided by OpenHarmony Flutter SDK, which is used to render Flutter pages in ArkUI. The principle is to use XComponent in ArkUI to customize the rendering content.
Modify the native page
import { router } from '@kit.ArkUI';
@Entry
@Component
struct Index {
build() {
Column() {
Text('Hello World').fontSize('50fp').fontWeight(FontWeight.Bold)
Blank().height(80)
Button('Jump to Flutter').onClick(() => {
router.pushUrl({ url: 'pages/FlutterContainerPage'})
})
}.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.width('100%')
.height('100%')
}
}
We add a button to the native page and jump to the Flutter page when the button is clicked.
Next
In the above example, the Flutter page opened each time is fixed. Next, we will explore how to dynamically jump to the Flutter page.
Top comments (0)