0
0
Fluttermobile~20 mins

Platform channels (MethodChannel) in Flutter - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Battery Level Screen
This screen shows the current battery level of the device by communicating with native platform code using MethodChannel.
Target UI
-------------------------
| Battery Level Screen   |
|-----------------------|
|                       |
|  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 MethodChannel to call native code to get battery level.
Update the text with the received battery level percentage.
Handle errors by showing 'Failed to get battery level.'
Starter Code
Flutter
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class BatteryLevelScreen extends StatefulWidget {
  @override
  State<BatteryLevelScreen> createState() => _BatteryLevelScreenState();
}

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

  String _batteryLevel = 'Battery Level: ?%';

  Future<void> _getBatteryLevel() async {
    // TODO: Call native code using platform.invokeMethod
    // and update _batteryLevel with the result or error
  }

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

class BatteryLevelScreen extends StatefulWidget {
  @override
  State<BatteryLevelScreen> createState() => _BatteryLevelScreenState();
}

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

  String _batteryLevel = 'Battery Level: ?%';

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

    if (!mounted) return;

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

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

This app uses a MethodChannel to communicate with native platform code to get the battery level.

We define a channel named samples.flutter.dev/battery. When the user taps the button, _getBatteryLevel calls invokeMethod('getBatteryLevel') which asks the native code for the battery percentage.

If successful, it updates the text to show the battery level. If it fails, it shows an error message.

This example teaches how Flutter apps can talk to native code to access device features not directly available in Flutter.

Final Result
Completed Screen
-------------------------
| Battery Level Screen   |
|-----------------------|
|                       |
|  Battery Level: 76%   |
|                       |
|  [Get Battery Level]   |
|                       |
-------------------------
User taps 'Get Battery Level' button.
App calls native code via MethodChannel.
Battery level number updates in the text.
If error occurs, text shows 'Failed to get battery level.'
Stretch Goal
Add a loading indicator while the battery level is being fetched.
💡 Hint
Use a boolean state variable to track loading and show CircularProgressIndicator instead of the button text during loading.