Monday, 17 August 2020

Creating a Flutter library for native android applications


Flutter side

1) Use the command flutter create -t module hello_world_module to create the project
2) Create your widget
//main.dart
import 'package:flutter/material.dart';
import 'dart:ui';

void main() => runApp(
MaterialApp(
home:chooseWidget(window.defaultRouteName)
)
);

Widget chooseWidget(String route) {
  switch (route) {
    case 'helloRoute':
      return Scaffold(
	  body:Center(
	    child:Container(
		color:Colors.green,
        child: Text('Hello from flutter',style:TextStyle(fontSize:20,color:Colors.black)),
      ) ));

    default:
      return Container();
  }
}

The reason I have used a switch case is because we can pass a parameter from the java side. Hence we can get multiple widgets from the same library.

Note: There are two ways to use this in a java based project
a) To link the source: this is preferred if we make changes to the android app and the flutter library side by side and we have the source code (Read here)
b) To link a built aar file: this is preferred if we have to distribute it as a library without the source code (in the following steps we will look into this)

3) use the command flutter build aar to build the library. The files will be built inside build\host\outputs\repo , this is the path required in your android project. After running the command flutter will display the steps to include the library in a native app, take a copy of it since it will be useful.

Native app side

1) Create an android project in android studio
2) In the app level build.gradle, insert the following outside the android block

repositories {
    maven {
        url '<PATH TO YOUR FLUTTER LIBRARY>/hello_world_module/build/host/outputs/repo'
    }
    maven {
        url 'https://storage.googleapis.com/download.flutter.io'
    }
}
     3) Inside the dependencies block add  
debugImplementation 'com.example.hello_world_module:flutter_debug:1.0'
  profileImplementation 'com.example.hello_world_module:flutter_profile:1.0'
  releaseImplementation 'com.example.hello_world_module:flutter_release:1.0'
4) Inside the android block add
compileOptions {
    sourceCompatibility 1.8
    targetCompatibility 1.8
  }
5) Inside buildTypes add (not sure if this is required)
profile {
     initWith debug
      }
When you save it wait for gradle sync to finish
6) Open activity_main.xml (app\src\main\res\layout), in design mode drag in a fragment. It will bring in the flutter fragment. Switch to code view and give some meaningful id and a tag

android:id="@+id/hellofragment"
android:tag="flutter_fragment"
7) Open mainActivity.java and change the code as
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import io.flutter.embedding.android.FlutterFragment;
import androidx.fragment.app.FragmentManager;

public class MainActivity extends AppCompatActivity {

    private FlutterFragment flutterFragment;
    private static final String TAG_FLUTTER_FRAGMENT = "flutter_fragment";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FlutterFragment flutterFragmentx;
        flutterFragment = FlutterFragment.withNewEngine().initialRoute("helloRoute").build();

        flutterFragmentx = (FlutterFragment) fragmentManager.findFragmentByTag(TAG_FLUTTER_FRAGMENT);

        // Create and attach a FlutterFragment if one does not exist.
        if (flutterFragmentx == null) {
            fragmentManager.beginTransaction().add(R.id.hellofragment, flutterFragment, TAG_FLUTTER_FRAGMENT).commit();
        }
        else {
            fragmentManager.beginTransaction().replace(R.id.hellofragment, flutterFragment, TAG_FLUTTER_FRAGMENT).commit();
        }
    }
}
Take note of the line initialRoute("helloRoute"). This is where we pass the parameter to our library.

References

  1. Codemagic
  2. Documentation-add Flutter Screen
  3. Documentation-add Flutter Fragment
  4. Youtube (video is for some older version, codes don’t work but the concept is the same)


No comments:

Post a Comment

Setting GitHub hooks in Jenkins

While setting up a Freestyle project in Jenkins we may need to set Github webhooks in Jenkins so that Jenkins will get notified each time th...