Flutter和原生交互---StreamController.broadcast

本文介绍了如何在Flutter插件中使用StreamController,避免在MainActivity中手动注册,实现在Android原生与Flutter之间的双向通信。通过创建StreamController,Flutter能够实时接收Android端的数据变化,简化了跨平台通信的流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一篇文章说道通过EventChannel使得Flutter监听Android原生的信息流变化,这种EventChannel需要我们在MainActivity中手动注册插件

通过StreamController.broadcast可以不用在MainActivity中手动注册插件(如果是在编写一个插件的话),而是通过真正的插件形式使得Flutter具有监听Android原生的能力

1.Flutter插件代码:注册并声明StreamController对象,并实现MethodChannel的setMethodCallHandler方法,

import 'dart:async';

import 'package:flutter/services.dart';

class GetTimePlugin {
  static const MethodChannel _channel = const MethodChannel('get_android_time');

  StreamController<String> _responseGetTime = new StreamController.broadcast();

  Stream<String> get responseGetTime => _responseGetTime.stream;

  SsoLoginPlugin() {
    _channel.setMethodCallHandler(_handler);
  }

  Future<dynamic> _handler(MethodCall methodCall) {
    if (methodCall.method == "onGetTimeCallback") {
      if ("success" == methodCall.arguments["result"]) {
        String time = methodCall.arguments["time"];
        _responseGetTime.add(time);
      } else {
        _responseGetTime.add(null);
      }
    }
    return null;
  }

  ///
  /// 获取time
  ///
  Future<String> get getTime async {
    final String version = await _channel.invokeMethod('getTime');
    return version;
  }

  dispose() {
    _responseGetTime.close();
  }
}

2.在Flutter中注册并调用回调方法:

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _time = 'Unknown';

  GetTimePlugin getTimePlugin = GetTimePlugin();

  @override
  void initState() {
    super.initState();

    getTimePlugin.responseGetCode.listen((event) {
      print("event: $event");
      setState(() {
        _time = event;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('time is: $_time'),
            SizedBox(
              height: 100,
            ),
            FlatButton(
                onPressed: () {
                  getTimePlugin.getTime();
                },
                child: Text("获取时间"))
          ],
        ),
      ),
    );
  }
}

3.原生逻辑中,通过注册的MethodChannel对象,调用上面注册的方法名称,实现Android通知Flutter:

Calendar calendar = Calendar.getInstance();
Map<String, String> result = new HashMap<>();
result.put("result", "success");
result.put("time", calendar.getTime().toString());
channel.invokeMethod("onGetTimeCallback", result);

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值