Zum Inhalt springen

HarmonyOS Flutter Practice: 20. Flutter integrates Amap, same-layer rendering

This article takes same-layer rendering as an example to introduce how to integrate Amap

For the complete code, see Flutter Harmony Demo

Overview

Dart side

The core code is as follows, using OhosView to carry the native view

OhosView(
viewType: 'com.shaohushuo.app/customView',
onPlatformViewCreated: _onPlatformViewCreated,
creationParams: const <String, dynamic>{'initParams': 'hello world'},
creationParamsCodec: const StandardMessageCodec(),
)

Where viewType is the name of the custom ohosView, onPlatformViewCreated is the creation completion callback, creationParams is the parameter passed in during creation, and creationParamsCodec is the parameter encoding format.

ArkTS side

Here we follow the example in „How to use PlatformView“. First, we need to create a view that displays Amap Maps. The core code is as follows:

Complete file AmapWidgetFactory.ets


MapsInitializer.setApiKey("e4147e927a1f63a0acff45cecf9419b5");
MapViewManager.getInstance().registerMapViewCreatedCallback((mapview?: MapView, mapViewName?: string) => {
if (!mapview) {
return;
}
let mapView = mapview; 
mapView.onCreate(); 
mapView.getMapAsync((map) => { 
let aMap: AMap = map; 
})
})

@Component
struct ButtonComponent { 
@Prop params: Params 
customView: AmapWidgetView = this.params.platformView as AmapWidgetView 

build() { 
Row() { 
MapViewComponent().width('100%').height('100%') 
} 
}
}

Next create a AmapWidgetFactory.ets

export class AmapWidgetFactory extends PlatformViewFactory { 
message: BinaryMessenger; 

constructor(message: BinaryMessenger, createArgsCodes: MessageCodec<Object>) { 
super(createArgsCodes); 
this.message = message; 
} 

public create(context: common.Context, viewId: number, args: Object): PlatformView { 
return new AmapWidgetView(context, viewId, args, this.message); 
}
}

Ultimately you need to create an AmapWidgetPlugin.ets

export class AmapWidgetPlugin implements FlutterPlugin { 
getUniqueClassName(): string { 
return 'AmapWidgetPlugin'; 
} 

onAttachedToEngine(binding: FlutterPluginBinding): void { 
binding.getPlatformViewRegistry()?. 
registerViewFactory('com.shaohushuo.app/customView', new AmapWidgetFactory(binding.getBinaryMessenger(), StandardMessageCodec.INSTANCE)); 
} 

onDetachedFromEngine(binding: FlutterPluginBinding): void {}
}

After the plug-in is created, remember to register the plug-in in EntryAbility

this.addPlugin(new AmapWidgetPlugin())

It should be noted that the view ID must be consistent on both sides, such as ‚com.shaohushuo.app/customView‘ here, otherwise it will not display properly

Screenshot

References

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert