Month: June 2022

  • Call swift native code from Flutter

    In this tutorial, we are going to call a simple swift method of AppDelegate.swift file from flutter.

    Let’s create a brand new flutter app by running the following command on your terminal

    flutter create ios_native

    Delete everything inside the method _incrementCounter() on your main.dart file and make it an async method.

     Future<void> _incrementCounter() async {
        const MethodChannel _channel =
            const MethodChannel("FlutterFramework/swift_native");
        final result = await _channel.invokeMethod('getSum');
        print("result from iOS native + Swift ${result}");
      }

    Now open your Runner.xcworkspace on Xcode and open AppDelegate.swift

    private func getSum() -> Int {
        return 2 + 2
     }

    Add the following code in the method didFinishLaunchingWithOptions and close the Xcode.

     let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
          let channel = FlutterMethodChannel(name: "FlutterFramework/swift_native",
                                             binaryMessenger: controller.binaryMessenger)
          channel.setMethodCallHandler({
              [weak self]  (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
              // This method is invoked on the UI thread.
              // Handle battery messages.
              guard call.method == "getSum" else {
                  result(FlutterMethodNotImplemented)
                  return
              }
    
              result(self?.getSum())
          })

    Now run the flutter app on the VSCode or Android Studio, if you click the floating button you will swift method returns 2 +2 = 4

    Call native Android code from Flutter

    Spread the love
  • How to change the status bar color in Flutter, Android only

    Changing the status bar color is very easy in Flutter. There are a few ways to do this.

    1. Globally in the main function
    import 'package:flutter/services.dart';
    
    void main() {
    
      SystemChrome.setSystemUIOverlayStyle(
        SystemUiOverlayStyle(
          statusBarColor: Colors.red,
        ),
      );
    
      runApp(
        MyApp()
      );
    }

    2. Globally in the MaterialApp widget in ThemeData

    return MaterialApp(
          title: 'FlutterFramework',
          debugShowCheckedModeBanner: false,
          themeMode: ThemeMode.light,
          theme: ThemeData(
            primaryColor: Colors.red,
            appBarTheme: AppBarTheme(
              systemOverlayStyle: SystemUiOverlayStyle(
                statusBarColor: Colors.red,
              ),
            ),
          ),
    );

    3. AppBar only

    AppBar(
      systemOverlayStyle: SystemUiOverlayStyle(
        statusBarColor: Colors.red,
      ),
    )

    Spread the love
  • Protocol in Swift

    Protocol in Swift

    Protocol in Swift

    In Swift, a protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

    Protocols are a way to define a set of requirements for any type to conform to. This means that you can use protocols to define the expected behavior for a particular task or piece of functionality, without worrying about how that functionality will be implemented. This makes it easy to write flexible and reusable code that can be used in a variety of contexts.

    For example, if you were creating a game, you might define a protocol called “Level” that specifies the properties and methods that all levels in the game must have. Then, any class that adopts the Level protocol must implement those properties and methods, so that they can be used in the game.

    Here is an example of how a protocol might be defined in Swift:

    protocol Level {
        var name: String { get set }
        func complete()
        func start()
    }
    

    In this example, the Level protocol defines two properties (name and difficulty) and two methods (complete and start). Any type that adopts the Level protocol must implement these properties and methods, so that it can be used in the game.

    To adopt a protocol, you write the protocol’s name after the class name, separated by a colon. Here is an example of how a class might adopt the Level protocol from the previous example:

    class ForestLevel: Level {
        var name: String = "Forest"
        var difficulty: Int = 3
    
        func complete() {
            print("You have completed the Forest level!")
        }
    
        func start() {
            print("Starting the Forest level...")
        }
    }
    

    In this example, the ForestLevel class adopts the Level protocol and provides an implementation of its requirements. This means that the ForestLevel class can be used as a level in the game, and it will have the properties and methods specified by the Level protocol.

    Spread the love