HarmonyOS Flutter in action: 25 - Hybrid Development Details - 5 - Navigating to Flutter Pages


Overview
In the previous chapter, we covered how to initialize the Flutter engine, and this article focuses on how to add and jump to the Flutter page.
Jump Principle
The principle of redirection is as follows:
Essentially jumping from one native page A to another native page B, but the difference is that page B is a page container with Flutter content embedded in it. At the same time, before opening page B, we need to notify Flutter to switch pages in advance, which uses the communication mechanism provided by Flutter, which is EventChannel.
Add a FlutterPage
In order to display Flutter content, we need to create a native page that acts as a container to host Flutter.
Add a page to the 'entry/src/main/etc/pages' directory, for example named 'FlutterContainerPage', right-click on the 'ohos/entry/src/main/ets/pages' directory, select New->Page->Empty Page and change the PageName to 'FlutterContainerPage', and click Finish, then modify the page to read 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 the OpenHarmony Flutter SDK for rendering Flutter pages in ArkUI. The idea is to use XComponent in ArkUI to customize the rendered content.
Modify native pages
import { router } from '@kit.ArkUI';
@Entry
@Component
struct Index {
build() {
Column() {
Text('Hello World').fontSize('50fp').fontWeight(FontWeight.Bold)
Blank().height(80)
Button('跳转Flutter').onClick(() => {
router.pushUrl({ url: 'pages/FlutterContainerPage'})
})
}.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.width('100%')
.height('100%')
}
}
We've added a button to the native page that will take you to the Flutter page when clicked.
Next
In the example above, the Flutter page is fixed every time it opens, so we'll explore how to dynamically jump to a Flutter page.
References
[How to add a jump FlutterEntry using hybrid development] (https://gitcode.com/openharmony-tpc/flutter_samples/blob/br_3.7.12-ohos-1.1.0/ohos/docs/04_development/ how to add a jump FlutterEntry.md using hybrid development)
Subscribe to my newsletter
Read articles from shaohushuo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
