鸿蒙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;
        }
      }
    });
  }
}
  • 效果展示
相关推荐
迷雾漫步者2 小时前
Flutter组件————FloatingActionButton
前端·flutter·dart
coder_pig7 小时前
📝小记:Ubuntu 部署 Jenkins 打包 Flutter APK
flutter·ubuntu·jenkins
捡芝麻丢西瓜9 小时前
flutter自学笔记5- dart 编码规范
flutter·dart
恋猫de小郭9 小时前
什么?Flutter 可能会被 SwiftUI/ArkUI 化?全新的 Flutter Roadmap
flutter·ios·swiftui
sunly_1 天前
Flutter:导航,tab切换,顶部固定,列表分页滚动
开发语言·javascript·flutter
敲代码的小强2 天前
Flutter项目兼容鸿蒙Next系统
flutter·华为·harmonyos
Zh-jie2 天前
flutter 快速实现侧边栏
前端·javascript·flutter
truemi.733 天前
flutter --no-color pub get 超时解决方法
android·flutter
王家视频教程图书馆3 天前
flutter 使用dio 请求go语言后台数据接口展示瀑布流图片
flutter
迷雾漫步者3 天前
Flutter组件————AppBar
flutter·跨平台·dart