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

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. Gloabbly 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, 
  ),
)

Create zip file in dart

Create zip file in dart

Creating a zip file in Dart is not that hard. Though there are not many packages right now to work with, so far we have only two packages which we can use to create zip, tar and others in dart.

If you have not installed dart yet please go to my post here.

Visit Pub Dev where you can find all kinds of packages for Flutter and Dart. Some packages work with both Flutter and Dart but not all of them.

Go to https://pub.dev/ and search zip you will find these two packages

  1. Archive https://pub.dev/packages/archive, for Dart and Flutter.
  2. Flutter Archive https://pub.dev/packages/flutter_archive for only Flutter project. 

In our case we will use the Archive package since we are testing in a console application. 

The Archive library currently supports the following decoders:

  • Zip (Archive)
  • Tar (Archive)
  • ZLib [Inflate decompression]
  • GZip [Inflate decompression]
  • BZip2 [decompression]

Add Archive package in your project 

With Dart

dart pub add archive

With Flutter

flutter pub add archive

Our pubspec.yaml

name: Create zip file in dart
description: A sample command-line application to create zip file
version: 1.0.0
homepage: https://flutterframework.com/

environment:
  sdk: '>=2.10.0 <3.0.0'

dependencies:
  archive: ^3.1.2

dev_dependencies:
  pedantic: ^1.9.0
  test: ^1.14.4

Our main zip.dart

import 'package:zip/zip.dart' as zip;

void main(List<String> arguments) {
  zip.createZip();
}

and lib/zip.dart

import 'dart:io';

import 'package:archive/archive.dart';
import 'package:archive/archive_io.dart';

void createZip() {
  final logDir = Directory.current.path + '/log';
  final zipLocation = Directory.current.path + '/log.zip';

  var encoder = ZipFileEncoder();
  encoder.zipDirectory(Directory(logDir), filename: zipLocation);

  // Manually create a zip of a directory and individual files.
  encoder.create(Directory.current.path + '/log2.zip');
  encoder.addFile(File('another_file.txt'));
  
  encoder.close();
}

Line number 10 creates a zip file in the destination file(line 8), from line 7 which is a directory containing few txt files.

You can create more zip file in the same encoder process, line 16 and more file line 17.

Download the source code from github.com

Flutter app design resources for iOS and Android

List of flutter app design resources

iOS Design Resources

  1. Download SF Symbols
  2. iOS 14 and iPad OS 14 Sketch Library
  3. iOS 14 and iPadOS 14 Sketch Kit
  4. iOS 14 nad iPad OS 14 XD Kit
  5. iOS 14 nad iPad OS 14 Photoshop Kit
  6. iOS 13 nad iPad OS 13 Sketch Library
  7. iOS 13 nad iPad OS 13 Keynote Kit
  8. App Store Marketing Guideline

Android Design Resources

  1. Google Play icon design specification
  2. Material Design
  3. Design Template Resources – Adobe Illustrator File
  4. Design Template Resources – Sketch File
  5. Design Template Resources – Photoshop File

MySQL and Maria DB connection with Dart language

MySQL and Maria DB connection with Dart language

Connect to MySQL or Maria DB server from Dart is very easy. We just need a couple of packages.

Create your pubspec.yaml and add mysqli as a dependency. And run

name: mysql
description: A sample command-line application.
# version: 1.0.0
# homepage: https://www.example.com
# author: sminrana <[email protected]>

environment:
  sdk: '>=2.0.0 <3.0.0'

dependencies:
  mysql1: ^0.17.1

dev_dependencies:
  test: ^1.0.0
pub get

Create a file name main.dart which looks like this

import 'dart:async';
import 'dart:io';

import 'package:mysql1/mysql1.dart';

Future main() async {
  final conn = await MySqlConnection.connect(ConnectionSettings(
      host: 'localhost', port: 3306, user: 'root', password: '1234', db: 'database_name'));


  // Create a table
  await conn.query(
      'CREATE TABLE users (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, name varchar(255), email varchar(255), age int)');

  // Insert some data
  var result = await conn.query(
      'insert into users (name, email, age) values (?, ?, ?)',
      ['Bob', '[email protected]', 25]);
  print('Inserted row id=${result.insertId}');

  // Query the database using a parameterized query
  var results = await conn
      .query('select name, email from users where id = ?', [result.insertId]);
  for (var row in results) {
    print('Name: ${row[0]}, email: ${row[1]}');
  }

  // Finally, close the connection
  await conn.close();
}

Here Future main async as an asynchronous dart main function which is required due to async call on line 7, here we must wait for await MySqlConnection to be finished its process.

Similarly we must wait for the task to be finished on line 12, we create a database table on this line.

Finally run the code by

dart main.dart
Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.