0
0
Fluttermobile~20 mins

Why platform channels bridge native code in Flutter - Build It to Prove It

Choose your learning style9 modes available
Build: Platform Channel Demo
This screen shows how Flutter communicates with native code using platform channels. It fetches the device's battery level from native code and displays it.
Target UI
-------------------------
| Platform Channel Demo |
|-----------------------|
| Battery Level: ?%     |
|                       |
| [Get Battery Level]    |
-------------------------
Display a text showing 'Battery Level: ?%' initially.
Add a button labeled 'Get Battery Level'.
When the button is tapped, use platform channels to call native code and get the current battery level.
Update the text with the received battery level percentage.
Handle errors gracefully by showing 'Battery Level: Unknown'.
Starter Code
Flutter
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: PlatformChannelDemo(),
    );
  }
}

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

  @override
  State<PlatformChannelDemo> createState() => _PlatformChannelDemoState();
}

class _PlatformChannelDemoState extends State<PlatformChannelDemo> {
  static const platform = MethodChannel('samples.flutter.dev/battery');

  String _batteryLevel = '?';

  Future<void> _getBatteryLevel() async {
    // TODO: Call native code using platform channel and update _batteryLevel
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Platform Channel Demo')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Battery Level: $_batteryLevel%'),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _getBatteryLevel,
              child: const Text('Get Battery Level'),
            ),
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Solution
Flutter
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: PlatformChannelDemo(),
    );
  }
}

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

  @override
  State<PlatformChannelDemo> createState() => _PlatformChannelDemoState();
}

class _PlatformChannelDemoState extends State<PlatformChannelDemo> {
  static const platform = MethodChannel('samples.flutter.dev/battery');

  String _batteryLevel = '?';

  Future<void> _getBatteryLevel() async {
    String batteryLevel;
    try {
      final int result = await platform.invokeMethod('getBatteryLevel');
      batteryLevel = result.toString();
    } on PlatformException {
      batteryLevel = 'Unknown';
    }

    if (!mounted) return;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Platform Channel Demo')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Battery Level: $_batteryLevel%'),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _getBatteryLevel,
              child: const Text('Get Battery Level'),
            ),
          ],
        ),
      ),
    );
  }
}

This Flutter app uses a MethodChannel named samples.flutter.dev/battery to communicate with native code.

When the user taps the 'Get Battery Level' button, the app calls invokeMethod('getBatteryLevel') on the channel. This sends a message to the native platform (Android or iOS) to run native code that returns the current battery level as an integer.

The app waits asynchronously for the result. If successful, it updates the displayed battery level. If there is an error (for example, native code not implemented), it shows 'Unknown'.

This shows how platform channels bridge Flutter and native code, allowing Flutter apps to use device features not available directly in Flutter.

Final Result
Completed Screen
-------------------------
| Platform Channel Demo |
|-----------------------|
| Battery Level: 85%    |
|                       |
| [Get Battery Level]    |
-------------------------
User taps 'Get Battery Level' button.
App calls native code via platform channel.
Battery level number updates on screen.
If error occurs, text shows 'Battery Level: Unknown'.
Stretch Goal
Add a loading indicator while fetching battery level.
💡 Hint
Use a boolean state variable to show CircularProgressIndicator instead of button text during loading.