0
0
Fluttermobile~7 mins

Platform channels (MethodChannel) in Flutter

Choose your learning style9 modes available
Introduction

Platform channels let your Flutter app talk to the phone's native code. This helps you use features Flutter doesn't have by itself.

You want to get the battery level from the phone's system.
You need to open a native camera app from Flutter.
You want to use a native sensor or hardware feature not in Flutter.
You want to send data from Flutter to Android or iOS code and get a reply.
Syntax
Flutter
final MethodChannel channel = MethodChannel('channel_name');

// To call native code
final result = await channel.invokeMethod('methodName', arguments);

// To handle calls from native code
channel.setMethodCallHandler((call) async {
  if (call.method == 'methodName') {
    return 'response';
  }
  return null;
});

The channel_name is a unique string to identify the communication line.

invokeMethod sends a message to native code and waits for a response.

Examples
This calls native code to get the battery level.
Flutter
final MethodChannel batteryChannel = MethodChannel('battery');

int batteryLevel = await batteryChannel.invokeMethod('getBatteryLevel');
This listens for native code asking Flutter to say hello.
Flutter
channel.setMethodCallHandler((call) async {
  if (call.method == 'sayHello') {
    return 'Hello from Flutter!';
  }
  return null;
});
Sample App

This Flutter app uses a MethodChannel to ask native code for the battery level. When you tap the button, it shows the battery percent or an error message.

Flutter
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  static const platform = MethodChannel('samples.flutter.dev/battery');
  String _batteryLevel = 'Unknown battery level.';

  Future<void> _getBatteryLevel() async {
    String batteryLevel;
    try {
      final int result = await platform.invokeMethod('getBatteryLevel');
      batteryLevel = 'Battery level at $result%.';
    } on PlatformException catch (e) {
      batteryLevel = 'Failed to get battery level: ${e.message}';
    }

    if (!mounted) return;

    setState(() {
      _batteryLevel = batteryLevel;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Battery Level Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(_batteryLevel),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: _getBatteryLevel,
                child: const Text('Get Battery Level'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Platform channels work by sending messages between Flutter and native code asynchronously.

You must write matching native code on Android (Kotlin/Java) and iOS (Swift/Obj-C) to handle the channel and methods.

Always handle errors in case the native side is not available or the method is missing.

Summary

Platform channels let Flutter talk to native phone code.

Use MethodChannel to send messages and get results.

Native code must listen and respond to these messages.