Method Channel in Flutter | Full Explanation With Examples

Method Channel in Flutter in Flutter is used to communicate with platform-specific code. You can use the native languages (Java/Kotlin for Android and Objective-C/Swift for iOS). This allows you to access platform-specific features, such as getting the device’s location. Here’s a complete example of how to use the Method Channel to get the device’s location:

Steps to use Method Channel in Flutter

  1. Set up the Flutter project: Create a new Flutter project or use an existing one.
  2. Add the required dependencies: In your pubspec.yaml file, or add the following dependencies:

We will fetch the location of the device using method channel so for that we can have the “geolocator” depedency. fluttertoast is used to show the toast.


dependencies:
  flutter:
    sdk: flutter

  # Add these dependencies for location services and method channel
  geolocator: ^7.6.2
  fluttertoast: ^8.0.8

Then, run > “flutter pub get" to install the new dependencies.

Implement the Flutter Code


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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: LocationScreen(),
    );
  }
}

class LocationScreen extends StatefulWidget {
  @override
  _LocationScreenState createState() => _LocationScreenState();
}

class _LocationScreenState extends State<LocationScreen> {
  static const platformChannel = MethodChannel('your_channel_name_here');

  String _locationText = 'Press the button to get location';

  Future<void> _getLocation() async {
    try {
      final result = await platformChannel.invokeMethod('getLocation');
      setState(() {
        _locationText = 'Location: $result';
      });
    } on PlatformException catch (e) {
      Fluttertoast.showToast(msg: "Error: ${e.message}");
      setState(() {
        _locationText = "Error getting location";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Location Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _locationText,
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _getLocation,
              child: Text('Get Location'),
            ),
          ],
        ),
      ),
    );
  }
}

Implement platform-specific code (Android/iOS):

  1. Now, you need to implement platform-specific code for getting the device’s location. For the sake of this example, we will provide the code for Android only.

In your Android project, navigate to android/app/src/main/java/com/example/your_app_name_here/ and create a new Java file (if not already created) named MainActivity.java. Then, add the following code:

For Android:


package com.example.your_app_name_here;

import android.os.Bundle;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.content.Context;

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "your_channel_name_here";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);
    }

    @Override
    public void configureFlutterEngine(FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);

        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler((call, result) -> {
                    if (call.method.equals("getLocation")) {
                        try {
                            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                            Location lastKnownLocation = null;
                            if (locationManager != null) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                                    if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                                        lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                    }
                                } else {
                                    lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                }
                            }

                            if (lastKnownLocation != null) {
                                double latitude = lastKnownLocation.getLatitude();
                                double longitude = lastKnownLocation.getLongitude();
                                result.success("Latitude: " + latitude + ", Longitude: " + longitude);
                            } else {
                                result.error("LOCATION_UNAVAILABLE", "Location data is not available.", null);
                            }
                        } catch (Exception e) {
                            result.error("ERROR", e.getMessage(), null);
                        }
                    } else {
                        result.notImplemented();
                    }
                });
    }
}

For IOS:

In your AppDelegate.swift file (located at ios/Runner/), update the application(_:didFinishLaunchingWithOptions:) method to implement the location retrieval functionality and communicate with Flutter using the MethodChannel. Here’s how:


import UIKit
import Flutter
import CoreLocation

@UIApplicationMain
class AppDelegate: FlutterAppDelegate {
    override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let controller: FlutterViewController = window?.rootViewController as! FlutterViewController

        // Register the MethodChannel
        let channel = FlutterMethodChannel(name: "your_channel_name_here", binaryMessenger: controller.binaryMessenger)
        channel.setMethodCallHandler { [weak self] call, result in
            if call.method == "getLocation" {
                self?.getLocation(result: result)
            } else {
                result(FlutterMethodNotImplemented)
            }
        }

        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    func getLocation(result: @escaping FlutterResult) {
        let locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
            // Note: You can use the `CLLocationManager` delegate methods to handle the location updates.
            // For simplicity, we'll use the last known location in this example.
            if let location = locationManager.location {
                let latitude = location.coordinate.latitude
                let longitude = location.coordinate.longitude
                result("Latitude: \(latitude), Longitude: \(longitude)")
            } else {
                result("Location data is not available.")
            }
        } else {
            result("Location services are not enabled.")
        }
    }
}

Now run the app to test your application.


Suggestions:

Binary Search Tree With Full Explanation And Examples

Difference Between Binary Tree and Binary Search Tree With Examples

Binary Search Tree Traversal With Full Examples And Explanation

Searching in Binary Search Tree With Full Explanation

Why String are immutable in Java | FlutterTPoint

How to show Image in Flutter

Method Channel in Flutter Full Explanation With Examples

Flutter Bloc State Management

GetX State Management in Flutter

State Management In Flutter

Provider in Flutter

Flutter Redux With Examples

Top 20 Flutter Interview Questions

Bottom Overflowed By Pixels Flutter

Pageview In Flutter And Its Types

Lottie Animation In Flutter Example

Alert Dialog In Flutter With Example

Flutter Inkwell With Example

Flutter Session Managements

Calling API In Flutter Using HTTP Request

What is Flutter : Creating Beautiful Native Apps

Flutter Widgets with Example

How to show Image in Flutter

Method Channel in Flutter Full Explanation With Examples

Flutter Bloc State Management

GetX State Management in Flutter

State Management In Flutter

Provider in Flutter

Flutter Redux With Examples

Top 20 Flutter Interview Questions

Bottom Overflowed By Pixels Flutter

Pageview In Flutter And Its Types

Lottie Animation In Flutter Example

Alert Dialog In Flutter With Example

Flutter Inkwell With Example

Flutter Session Managements

Calling API In Flutter Using HTTP Request

What is Flutter : Creating Beautiful Native Apps

Flutter Widgets with Example

FutureBuilder in Flutter With Examples

Donโ€™t miss new tips!

We donโ€™t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment

Translate ยป
Scroll to Top