CodeBlanks Logo Icon CodeBlanks

What is MethodChannel?

Bridge Dart to native with MethodChannel.

What is MethodChannel?

MethodChannel is a bridge used to communicate between Dart code and platform-specific native code (Kotlin/Java on Android, Swift/Objective-C on iOS). The channel name must be the same on both sides; messages are sent and received through this name.

const channel = MethodChannel('samples.flutter.dev/battery');

Channel name

Each MethodChannel is created with a unique name. The same name is used on both the Dart side and the native side. It is usually written in a reverse domain format, for example samples.flutter.dev/battery. If the name differs, messages do not reach the other side.

const channel = MethodChannel('samples.flutter.dev/battery');

Practice Create a MethodChannel

Create a MethodChannel with the name 'samples.flutter.dev/battery' and print 'ok'.

Starter code

main.dart
class MethodChannel {
  final String name;
  MethodChannel(this.name);
}

void main() {
  // MethodChannel oluştur
  // 'ok' yazdır
}

Sample solution

main.dart
class MethodChannel {
  final String name;
  MethodChannel(this.name);
}

void main() {
  const channel = MethodChannel('samples.flutter.dev/battery');
  print('ok');
}

Expected output

ok

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the purpose of MethodChannel?

  • To run database queries
  • To communicate between Dart and native platform code Correct answer
  • To carry data between two widgets
  • To send HTTP requests

Explanation: MethodChannel acts as a bridge between Dart and native code; it has nothing to do with widget data, HTTP, or databases.

2 Create a MethodChannel

Question
const channel = ____('samples.flutter.dev/battery');
Answer
const channel = MethodChannel('samples.flutter.dev/battery');

Explanation: To create a MethodChannel you call the MethodChannel constructor and pass the channel name as a parameter.

3 MethodChannel parts

Term Meaning
MethodChannel Dart-native bridge
native Platform-specific code
channel Communication channel
'samples.flutter.dev/battery' Channel name

All lessons in Advanced