1// Copyright 2014 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5@TestOn('chrome') // Uses web-only Flutter SDK
6library;
7
8import 'dart:ui_web' as ui_web;
9
10import 'package:flutter/services.dart';
11import 'package:flutter_test/flutter_test.dart';
12import 'package:flutter_web_plugins/flutter_web_plugins.dart';
13
14class TestPlugin {
15 static void registerWith(Registrar registrar) {
16 final MethodChannel channel = MethodChannel(
17 'test_plugin',
18 const StandardMethodCodec(),
19 registrar.messenger,
20 );
21 final TestPlugin testPlugin = TestPlugin();
22 channel.setMethodCallHandler(testPlugin.handleMethodCall);
23 }
24
25 static final List<String> calledMethods = <String>[];
26
27 Future<void> handleMethodCall(MethodCall call) async {
28 calledMethods.add(call.method);
29 }
30}
31
32void main() {
33 // Disabling tester emulation because this test relies on real message channel communication.
34 ui_web.debugEmulateFlutterTesterEnvironment = false;
35
36 group('Plugin Registry', () {
37 setUp(() {
38 TestWidgetsFlutterBinding.ensureInitialized();
39 webPluginRegistry.registerMessageHandler();
40 final Registrar registrar = webPluginRegistry.registrarFor(TestPlugin);
41 TestPlugin.registerWith(registrar);
42 });
43
44 test('can register a plugin', () {
45 TestPlugin.calledMethods.clear();
46
47 const MethodChannel frameworkChannel = MethodChannel('test_plugin');
48 frameworkChannel.invokeMethod<void>('test1');
49
50 expect(TestPlugin.calledMethods, equals(<String>['test1']));
51 });
52
53 test('can send a message from the plugin to the framework', () async {
54 const StandardMessageCodec codec = StandardMessageCodec();
55
56 final List<String> loggedMessages = <String>[];
57 ServicesBinding.instance.defaultBinaryMessenger.setMessageHandler('test_send', (
58 ByteData? data,
59 ) {
60 loggedMessages.add(codec.decodeMessage(data)! as String);
61 return Future<ByteData?>.value();
62 });
63
64 await pluginBinaryMessenger.send('test_send', codec.encodeMessage('hello'));
65 expect(loggedMessages, equals(<String>['hello']));
66
67 await pluginBinaryMessenger.send('test_send', codec.encodeMessage('world'));
68 expect(loggedMessages, equals(<String>['hello', 'world']));
69
70 ServicesBinding.instance.defaultBinaryMessenger.setMessageHandler('test_send', null);
71 });
72 });
73}
74

Provided by KDAB

Privacy Policy
Learn more about Flutter for embedded and desktop on industrialflutter.com