Method Channel In Flutter

Method Channel In Flutter : Flutter platform channel using calls android and iOS. For example open the camera get result, contact picker get result, activity open get result etc.

  • Flutter and android native interaction
  • Flutter Method channel
  • Flutter native communication
  • Flutter android and ios communication
  • Flutter applicatiom, we have send to messages a host on iOS or Android of the over a platform channel.
  • The host listens on the platform channel and receives the message. It then uses any platform-specific APIs using the native programming language and sends back a response to the Flutter portion of the app.
  • A named channel for communicating with platform plugins using asynchronous
  • Platform channel uses standard message codec that supports efficient binary serialization of simple JSON-like values of types boolean, number, String, byte buffer, list, and map. The serialization and deserialization of these values to and from messages happen automatically when we send and receive values.
  • The generic argument T of the method can be inferred by the surrounding context, or provided explicitly. If it does not match the returned type of the channel, a [TypeError] will be thrown at runtime. T cannot be a class with generics other than dynamic. For example, Map<String, String> is not supported but Map<dynamic, dynamic> or Map is.

Flutter defines three different Channels:

  1. Method Channel: Used to pass method calls.
  2. Event Channel: Used for data flow information communication.
  3. Basic Message Channel: Used to transfer strings and semi-structured information.

Each Channel contains three member variables.

  • Name: Represents the unique identifier of Channel. Channel can contain more than one, but name is unique.
  • Messageager: Binary Messenger, a tool for sending and receiving messages.
  • Codec: a codec representing a message.

InvokedMethod()

Future invokeMethod(String method, [ dynamic arguments ]) async { }
1) [invokeListMethod], for automatically returning typed lists.
2) [invokeMapMethod], for automatically returning typed maps.
3) [StandardMessageCodec] which defines the payload values supported by [StandardMethodCodec].
4) [JSONMessageCodec] which defines the payload values supported by [JSONMethodCodec].

Method Channel In Flutter

Step 1:
class MainActivity : FlutterActivity() { }
First run flutter which is android activity.

Step 2:
static const MethodChannel _channel = const MethodChannel(‘flutter_plugin’);
Create an instance of MethodChannel class with arguments: flutterView as the message sender/receiver and channel name.

Note:

  • Flutter doesn’t provide a default style in the Android module, you must add them manually and set them in the manifest file for native activity that you are creating .
  • If code the change native can’t be hot reloaded or hot restarted support.
  • All channel names used in a single app must be unique.
  • Starting a method with underscore _ automatically turns it into a private one!

Method Channel In Flutter :

FlutterPlugin.kt

package com.fluttertutorial.flutter_plugin

import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
import java.util.HashMap

class FlutterPlugin: MethodCallHandler {
  companion object {
    @JvmStatic
    fun registerWith(registrar: Registrar) {
      val channel = MethodChannel(registrar.messenger(), "flutter_plugin")
      channel.setMethodCallHandler(FlutterPlugin())
    }
  }

  override fun onMethodCall(call: MethodCall, result: Result) {
    if (call.method == "plugin") {
      /*val data = HashMap<String, Any>()
      contact["fullName"] = "Flutter Tutorial"
      contact["phoneNumber"] = "0000000000"
      */

      val data = ArrayList<String>()
      data.add("Flutter")
      data.add("Tutorial")
      result.success(data)
    } else {
      result.notImplemented()
    }
  }
}

flutter_plugin.dart

import 'dart:async';

import 'package:flutter/services.dart';

class FlutterPlugin {
  static const MethodChannel _channel =
      const MethodChannel('flutter_plugin');

  /*static Future<Contact> get platformVersion async {
    final Map<dynamic, dynamic> result = await _channel.invokeMethod('getPlatformVersion');
    return new Contact.fromMap(result);
  }*/

  /*static Future<Map<dynamic, dynamic>> get platformVersion async {
    final Map<dynamic, dynamic> result = await _channel.invokeMethod('getPlatformVersion');
    return result;
  }*/

  /*static Future<List<dynamic>> get platformVersion async {
    final List<dynamic> result = await _channel.invokeMethod('getPlatformVersion');
    return result;
  }*/

  static Future<List> get platformVersion async {
    final List result = await _channel.invokeMethod('plugin');
    return result;
  }
}

class Contact {
  Contact({this.fullName, this.phoneNumber});

  factory Contact.fromMap(Map<dynamic, dynamic> map) => new Contact(
      fullName: map['fullName'],
      phoneNumber: map['phoneNumber']);

  /// The full name of the contact, e.g. "Dr. Daniel Higgens Jr.".
  final String fullName;

  /// The phone number of the contact.
  final String phoneNumber;

  @override
  String toString() => '$fullName: $phoneNumber';
}

main.dart

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

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

void main() => runApp(MyApp());

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

class _MyAppState extends State<MyApp> {
  List _get;
  //Map<dynamic, dynamic> _get;

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

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    List get;
    //Map<dynamic, dynamic> get;

    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      get = await FlutterPlugin.platformVersion;
    } on PlatformException {

    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _get = get;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text(_get.toString()),
        ),
      ),
    );
  }
}

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in