Bird
Raised Fist0
Fluttermobile~5 mins

Why platform channels bridge native code in Flutter

Choose your learning style10 modes available
Introduction

Platform channels let Flutter apps talk to native code on Android and iOS. This helps use features Flutter doesn't have by itself.

When you want to use a phone feature Flutter doesn't support yet, like sensors or camera controls.
When you need to run native code for better performance or access system APIs.
When you want to reuse existing native code in your Flutter app.
When you want to handle platform-specific tasks like notifications or background services.
When you need to get data from native libraries or SDKs.
Syntax
Flutter
final platform = MethodChannel('channel_name');

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

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

The MethodChannel connects Flutter and native code using a unique channel name.

Use invokeMethod to ask native code to do something and get a result back.

Examples
This example calls native code to get the battery level from the device.
Flutter
final platform = MethodChannel('samples.flutter.dev/battery');

Future<int> getBatteryLevel() async {
  final int batteryLevel = await platform.invokeMethod('getBatteryLevel');
  return batteryLevel;
}
This example listens for native code to ask Flutter to show a toast message.
Flutter
platform.setMethodCallHandler((call) async {
  if (call.method == 'showToast') {
    final message = call.arguments as String;
    // Show toast on Flutter side
    return 'Toast shown';
  }
  return null;
});
Sample App

This Flutter app uses a platform channel to ask native code for the battery level. When you tap the button, it shows the battery percentage.

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

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

class MyApp extends StatefulWidget {
  @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 is $result%.';
    } on PlatformException catch (e) {
      batteryLevel = 'Failed to get battery level: ${e.message}';
    }
    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),
              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 implement the native side code separately in Android (Kotlin/Java) and iOS (Swift/Objective-C).

Always handle errors because native calls can fail or be unavailable on some devices.

Summary

Platform channels let Flutter apps use native device features.

They send messages between Flutter and native code using a named channel.

This helps Flutter apps do things they can't do alone.

Practice

(1/5)
1. Why do Flutter apps use platform channels to communicate with native code?
easy
A. To speed up Flutter's UI rendering
B. To access device features not available in Flutter alone
C. To replace Flutter widgets with native widgets
D. To avoid using Dart language

Solution

  1. Step 1: Understand Flutter's limitations

    Flutter cannot directly access some device features like sensors or camera APIs.
  2. Step 2: Role of platform channels

    Platform channels let Flutter send messages to native code that can access these features.
  3. Final Answer:

    To access device features not available in Flutter alone -> Option B
  4. Quick Check:

    Platform channels = access native features [OK]
Hint: Remember: platform channels bridge Flutter and native features [OK]
Common Mistakes:
  • Thinking platform channels speed up UI rendering
  • Confusing platform channels with widget replacement
  • Believing platform channels avoid Dart usage
2. Which of the following is the correct way to create a platform channel in Flutter?
easy
A. PlatformChannel('com.example.channel')
B. NativeChannel('com.example.channel')
C. MethodChannel('com.example.channel')
D. FlutterChannel('com.example.channel')

Solution

  1. Step 1: Recall Flutter's platform channel class

    Flutter uses the MethodChannel class to create platform channels.
  2. Step 2: Check the correct constructor usage

    The constructor takes a string name like 'com.example.channel'.
  3. Final Answer:

    MethodChannel('com.example.channel') -> Option C
  4. Quick Check:

    MethodChannel = correct class name [OK]
Hint: MethodChannel is the official Flutter class for platform channels [OK]
Common Mistakes:
  • Using wrong class names like PlatformChannel or NativeChannel
  • Confusing the channel name with class name
  • Omitting the channel name string
3. What will happen when Flutter code calls a native method via platform channel but the native side does not implement that method?
medium
A. Flutter receives a PlatformException error
B. Flutter app crashes immediately
C. Flutter ignores the call silently
D. Flutter retries the call automatically

Solution

  1. Step 1: Understand platform channel error handling

    If native code does not implement the called method, Flutter gets an error response.
  2. Step 2: Identify the error type

    Flutter throws a PlatformException to indicate the method is missing.
  3. Final Answer:

    Flutter receives a PlatformException error -> Option A
  4. Quick Check:

    Missing native method = PlatformException [OK]
Hint: Missing native method triggers PlatformException in Flutter [OK]
Common Mistakes:
  • Assuming app crashes without error handling
  • Thinking Flutter ignores missing methods silently
  • Believing Flutter retries calls automatically
4. Identify the error in this Flutter platform channel code snippet:
final channel = MethodChannel('com.example.channel');
channel.invokeMethod('getBatteryLevel');
medium
A. MethodChannel cannot be final
B. Wrong channel name format
C. invokeMethod should be invokeNativeMethod
D. Missing await keyword for async call

Solution

  1. Step 1: Check method invocation style

    invokeMethod returns a Future and should be awaited or handled asynchronously.
  2. Step 2: Identify missing async handling

    Code calls invokeMethod without await or then, which can cause unhandled results.
  3. Final Answer:

    Missing await keyword for async call -> Option D
  4. Quick Check:

    invokeMethod requires await or async handling [OK]
Hint: Always await invokeMethod calls to handle async results [OK]
Common Mistakes:
  • Ignoring async nature of invokeMethod
  • Using wrong method names
  • Misunderstanding final keyword usage
5. You want to get the device's battery level using platform channels. Which sequence correctly describes the communication flow?
hard
A. Flutter sends message via MethodChannel -> Native code receives and returns battery level -> Flutter receives result
B. Native code sends battery level to Flutter -> Flutter processes and sends back confirmation
C. Flutter directly reads battery level without native code
D. Flutter uses platform channel to update UI without native interaction

Solution

  1. Step 1: Understand platform channel message flow

    Flutter initiates a message via MethodChannel to native code requesting data.
  2. Step 2: Native code processes and replies

    Native code handles the request, gets battery level, and sends it back.
  3. Step 3: Flutter receives and uses the result

    Flutter receives the battery level and can update UI accordingly.
  4. Final Answer:

    Flutter sends message via MethodChannel -> Native code receives and returns battery level -> Flutter receives result -> Option A
  5. Quick Check:

    Message flow = Flutter -> Native -> Flutter [OK]
Hint: Platform channels send request from Flutter, native replies, Flutter receives [OK]
Common Mistakes:
  • Thinking native initiates communication
  • Assuming Flutter reads battery without native code
  • Confusing message direction and flow
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard