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

Posted 泸沽烟火

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter和原生交互---StreamController.broadcast相关的知识,希望对你有一定的参考价值。

上一篇文章说道通过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);

 

以上是关于Flutter和原生交互---StreamController.broadcast的主要内容,如果未能解决你的问题,请参考以下文章

Flutter和原生交互---EventChannel

Flutter和原生交互---EventChannel

Flutter和原生交互---EventChannel

Flutter与原生交互

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

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