Writing Android Specific Code

Writing Code Specifically for Android

Flutter enables access to platform-specific features like the camera, battery, and browser using a simple messaging protocol. A shared MessageChannel connects the Flutter code (client) and the platform code (host). The client sends messages through the channel, the host listens, performs the required actions, and sends the result back via the same channel.To implement iOS-specific code in a Flutter project.


Step 1: Create a Flutter Project

  1. Open a terminal and create a new Flutter project. For this example, name the project flutter_browser_ios_app


flutter create flutter_browser_ios_app
cd flutter_browser_ios_app

Open the project in Android Studio or Visual Studio Code.

Step 2: Add a MethodChannel in Flutter Code

Navigate to the lib/main.dart file in your project and add the following Flutter code to set up the MethodChannel:



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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'iOS Browser Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: MyHomePage(title: 'Open Safari Browser'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;

  MyHomePage({Key? key, required this.title}) : super(key: key);

  // Set up the MethodChannel
  static const platform = MethodChannel('custom.flutter.channel/browser');

  // Define a method to invoke the platform-specific code
  Future<void> openBrowser() async {
    try {
      await platform.invokeMethod('openBrowser', <String, String>{
        'url': 'https://example.com', // Replace with a generic URL
      });
    } on PlatformException catch (e) {
      print("Error: \${e.message}");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(title)),
      body: Center(
        child: ElevatedButton(
          onPressed: openBrowser,
          child: Text('Open Browser'),
        ),
      ),
    );
  }
}

iOS Code (Swift)

  • Navigate to the iOS folder in your Flutter project.
  • Open the project in Xcode by double-clicking the Runner.xcworkspace file.

Import Required Libraries

In AppDelegate.swift, add the following imports:



import UIKit
import Flutter

Set up the Method Channel

In the AppDelegate.swift file, modify the application function to set up the Method Channel and handle the method calls:



import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    private let channelName = "com.appleapp.flutter/browser"

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        let controller: FlutterViewController = window?.rootViewController as! FlutterViewController
        let browserChannel = FlutterMethodChannel(
            name: channelName,
            binaryMessenger: controller.binaryMessenger
        )

        browserChannel.setMethodCallHandler { [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in
            if call.method == "openBrowser" {
                guard let args = call.arguments as? [String: String],
                      let urlString = args["url"],
                      let url = URL(string: urlString) else {
                    result(FlutterError(
                        code: "INVALID_URL",
                        message: "The provided URL is invalid",
                        details: nil
                    ))
                    return
                }
                self?.openBrowser(url: url, result: result)
            } else {
                result(FlutterMethodNotImplemented)
            }
        }

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

    private func openBrowser(url: URL, result: FlutterResult) {
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:]) { success in
                result(success)
            }
        } else {
            result(FlutterError(
                code: "CANNOT_OPEN_URL",
                message: "Unable to open the browser for the given URL",
                details: nil
            ))
        }
    }
}
Previous Post Next Post