Working with Platform Channels in Flutter

Tutorial 2 of 5

Working with Platform Channels in Flutter

1. Introduction

In this tutorial, we aim to understand and work with Platform Channels in Flutter. Platform channels provide a simple mechanism for code in Dart to communicate with platform-specific code in Kotlin (on Android) or Swift (on iOS).

By the end of this tutorial, you will learn:

  • What Platform Channels are and why they are important
  • How to use Platform Channels in Flutter
  • How to call native functions from Dart

The prerequisites for this tutorial are:

  • Basic understanding of Flutter and Dart
  • Working knowledge of Android (Kotlin) or iOS (Swift) development would be beneficial but not necessary

2. Step-by-Step Guide

Platform Channels are essentially the bridge between the Dart code and the native code. Flutter uses a flexible system that allows you to call platform-specific APIs whether available in Kotlin or Swift.

  • MethodChannel: This is used for sending messages that correspond to method calls.
  • EventChannel: This is used for data streams.

The messages are passed and encoded using a standard message codec, and they support a variety of data types like int, String, etc.

3. Code Examples

Here is an example of how to create a MethodChannel and use it to access the battery level on an Android device:

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

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

  // Get battery level.
  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}'.";
    }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            ElevatedButton(
              child: Text('Get Battery Level'),
              onPressed: _getBatteryLevel,
            ),
            Text(_batteryLevel),
          ],
        ),
      ),
    );
  }
}

This creates a MethodChannel with the specified name. It then uses this channel to invoke a method that gets the battery level.

4. Summary

In this tutorial, we have covered the basics of Platform Channels in Flutter, what they are, why they are important, and how to use them to invoke platform-specific code from Dart.

Your next steps could be to explore how to use EventChannels for data streams and how to implement the native method in Kotlin or Swift.

5. Practice Exercises

  1. Try to create a Flutter app that uses platform channels to access the device's current location.
  2. Create a Flutter app that uses platform channels to retrieve a list of installed apps.

Remember, practice is key to mastering any concept, so make sure to try out these exercises. Also, keep exploring more about Flutter and its features. Happy coding!