Platform channels let your Flutter app talk to the phone's native code. This helps you use features Flutter doesn't have by itself.
Platform channels (MethodChannel) in 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.
final MethodChannel batteryChannel = MethodChannel('battery'); int batteryLevel = await batteryChannel.invokeMethod('getBatteryLevel');
channel.setMethodCallHandler((call) async {
if (call.method == 'sayHello') {
return 'Hello from Flutter!';
}
return null;
});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.
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'), ), ], ), ), ), ); } }
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.
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.
Practice
MethodChannel in Flutter?Solution
Step 1: Understand Flutter and native code interaction
Flutter apps sometimes need to use features only available in native code like Android or iOS.Step 2: Role of MethodChannel
MethodChannelis the way Flutter sends messages to native code and gets results back.Final Answer:
To communicate between Flutter and native platform code -> Option BQuick Check:
MethodChannel = Flutter-native communication [OK]
- Thinking MethodChannel creates UI widgets
- Confusing MethodChannel with navigation or animation
- Assuming MethodChannel runs only in Flutter without native code
MethodChannel in Flutter?Solution
Step 1: Check MethodChannel constructor usage
The constructor requires a string name to identify the channel, e.g., 'com.example.channel'.Step 2: Validate options
MethodChannel channel = MethodChannel('com.example.channel'); correctly usesMethodChannel('com.example.channel'). Options A, C, and D are invalid syntax or missing required parameters.Final Answer:
MethodChannel channel = MethodChannel('com.example.channel'); -> Option CQuick Check:
MethodChannel needs a channel name string [OK]
- Omitting the channel name string
- Using 'new' keyword unnecessarily
- Calling non-existent create() method
final channel = MethodChannel('com.example.channel');
String message = await channel.invokeMethod('greet');
print(message);Solution
Step 1: Understand invokeMethod behavior
TheinvokeMethodsends a message to native code and waits for a response.Step 2: Native returns "Hello from native" string
The returned string is assigned tomessageand printed.Final Answer:
"Hello from native" -> Option DQuick Check:
invokeMethod returns native response string [OK]
- Assuming invokeMethod returns null if native responds
- Expecting invokeMethod to print automatically
- Ignoring await causing Future object print
final channel = MethodChannel('com.example.channel');
channel.invokeMethod('getData');
print('Data received');Solution
Step 1: Check asynchronous call usage
invokeMethodreturns a Future and should be awaited to get the result before proceeding.Step 2: Analyze print timing
Without await,print('Data received')runs immediately, before native response arrives.Final Answer:
invokeMethod is not awaited, so print runs before data arrives -> Option AQuick Check:
Always await invokeMethod for native response [OK]
- Not awaiting invokeMethod causing timing issues
- Thinking MethodChannel name is invalid without reason
- Expecting invokeMethod to take a callback parameter
MethodChannel? Choose the correct sequence.Solution
Step 1: Setup MethodChannel in Flutter
Create a channel with a unique name to communicate with native code.Step 2: Call invokeMethod with method name
Flutter sends 'getBatteryLevel' request to native side.Step 3: Setup native Android MethodCallHandler
Native code listens on the same channel name and handles method calls.Step 4: Native code returns battery level
Native side gets battery info and sends it back.Step 5: Flutter receives and uses battery level
Flutter awaits response and uses the data.Final Answer:
1. Create MethodChannel in Flutter with a name 2. Call invokeMethod('getBatteryLevel') 3. In Android native code, set MethodCallHandler on same channel name 4. Handle 'getBatteryLevel' method and return battery level 5. Flutter receives battery level response -> Option AQuick Check:
Flutter-native communication needs matching channel and method handling [OK]
- Skipping native code setup for MethodCallHandler
- Calling invokeMethod without method name
- Using different channel names on Flutter and native sides
Ready to prove it?
Pass the test and this pattern moves unknown
