鸿蒙harmonyos next flutter通信之MethodChannel获取设备信息

本文将通过MethodChannel获取设备信息,以此来演练MethodChannel用法。

  • 建立channel

flutter代码:

MethodChannel methodChannel = MethodChannel("com.xmg.test");

ohos代码:

private channel: MethodChannel | null = null

this.channel = new MethodChannel(flutterEngine.dartExecutor.getBinaryMessenger(), 'com.xmg.test')

this.channel.setMethodCallHandler({
      onMethodCall(call: MethodCall, result: MethodResult): void {
        switch (call.method) {
          case 'getDeviceInfo':
            result.success(deviceInfo.displayVersion);
            break;
          default:
            result.notImplemented
            break;
        }
      }
    });

注意:channelName必须一致。这里都叫com.xmg.test

  • flutter侧调用

    void _getDeviceInfo() async{
        deviceInfo = await methodChannel.invokeMethod('getDeviceInfo');
        setState(() {
        });
      }
    
  • 完整代码

flutter完整代码:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'MethodChannel获取设备信息'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  MethodChannel methodChannel = MethodChannel("com.xmg.test");
  String deviceInfo = "";

  void _getDeviceInfo() async{
    deviceInfo = await methodChannel.invokeMethod('getDeviceInfo');
    setState(() {
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              deviceInfo,
            ),
            ElevatedButton(onPressed: () {
              _getDeviceInfo();
            }, child: Text("获取设备版本号"))
          ],
        ),
      ),
    );
  }
}

ohos完整代码:

import { FlutterAbility, FlutterEngine, MethodCall, MethodChannel, MethodResult } from '@ohos/flutter_ohos';
import { GeneratedPluginRegistrant } from '../plugins/GeneratedPluginRegistrant';
import deviceInfo from '@ohos.deviceInfo'

export default class EntryAbility extends FlutterAbility {
  private channel: MethodChannel | null = null

  configureFlutterEngine(flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    GeneratedPluginRegistrant.registerWith(flutterEngine)

    this.channel = new MethodChannel(flutterEngine.dartExecutor.getBinaryMessenger(), 'com.xmg.test')
    this.channel.setMethodCallHandler({
      onMethodCall(call: MethodCall, result: MethodResult): void {
        switch (call.method) {
          case 'getDeviceInfo':
            result.success(deviceInfo.displayVersion);
            break;
          default:
            result.notImplemented
            break;
        }
      }
    });
  }
}
  • 效果展示
相关推荐
比格丽巴格丽抱6 小时前
flutter项目苹果编译运行打包上线
flutter·ios
SoaringHeart6 小时前
Flutter进阶:基于 MLKit 的 OCR 文字识别
前端·flutter
AiFlutter11 小时前
Flutter通过 Coap发送组播
flutter
嘟嘟叽1 天前
初学 flutter 环境变量配置
flutter
iFlyCai1 天前
深入理解Flutter生命周期函数之StatefulWidget(一)
flutter·生命周期·dart·statefulwidget
sunly_1 天前
Flutter:photo_view图片预览功能
android·javascript·flutter
Summer不秃2 天前
Flutter中sqflite的使用案例
flutter
sunly_2 天前
Flutter:TweenAnimationBuilder自定义隐式动画
flutter
AiFlutter2 天前
Flutter-Web首次加载时添加动画
前端·flutter
Allen Su2 天前
【Flutter 问题系列第 84 篇】如何清除指定网络图片的缓存
flutter·缓存·如何清除指定网络图片的缓存·网络图片缓存