Skip to main content

Flutter How to Start Android Activity from Flutter View


Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View.

Create a Project for this Android Activity Flutter View Demo

Create a Project
  1. From File menu select the New Flutter Project
  2. Enter the project name
  3. Select the AndroidX support and click on next
  4. After the above, we step click on Finish
    We will have the following project structure created. Flutter Project Structure

Create the Second Activity in Android


Just go to the android folder and open it in separate windows. We will have the following project structure.





Start Activity From Flutter View




Create the Activity

Just right click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project sync completed.

Update the project build config build.gradle file

Due to some problem, it may happen that we have some error in the build.gradle file.

   ext.kotlin_version = '1.3.41' '1.2.71'

Now, remove the '1.2.71' from the ext.kolin_version and start the sync again. If all these issues resolved then the sync will be completed successfully;

Go to ou newly created activity and add the dependency by clicking on Alt+Enter key. Or alternatively, you can add the appcompat dependency directly into your build.gradle files like below.


dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'androidx.appcompat:appcompat:1.1.0'
}

Create the Theme for our activity

Now, we need to create an AppCompat Theme for our activity. So go to res->value->style.xml files and add the theme.

<style name="MyTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">#7B1FA2</item>
        <item name="colorPrimaryDark">#4A148C</item>
        <item name="colorAccent">@android:color/holo_blue_light</item>
        <item name="android:windowBackground">@drawable/launch_background</item>
    </style>

Set the theme to Android Activity

Open the file AndroidMenifest.xml file and set the theme like below.

 <activity android:name=".KotlinActivity"
            android:theme="@style/MyTheme">  
 </activity>

Create the method to start the second Activity

Go to the main activity again and add the required method as like below.

package com.nplix.android_activity_demo

import android.content.Intent
import android.os.Bundle

import io.flutter.app.FlutterActivity
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
  private val CHANNEL = "com.startActivity/testChannel"
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    GeneratedPluginRegistrant.registerWith(this)

    MethodChannel(flutterView,CHANNEL).setMethodCallHandler{ call,result ->
      if(call.method.equals("StartSecondActivity")){
        val intent=Intent(this,KotlinActivity::class.java)
        startActivity(intent)
        result.success("ActivityStarted")
      }
      else{
        result.notImplemented()
      }
    }
  }
}

So what we are doing here?
  • First of all, we are defining a channel using the line private val CHANNEL = "com.startActivity/testChannel" we will use this to create the platform from the flutter view.
  • Create a method handler in the line

MethodChannel(flutterView,CHANNEL).setMethodCallHandler{ call,result ->
      if(call.method.equals("StartSecondActivity")){
        val intent=Intent(this,KotlinActivity::class.java)
        startActivity(intent)
        result.success("ActivityStarted")
      }
      else{
        result.notImplemented()
      }
    }

  • Third, we are comparing the called method using the if condition and starting the activity.
  • In the case method not match then we will throw the method not implemented the method using the below line.

 else{
        result.notImplemented()
      }

Call the Android Method from Flutter View

Now time call the android method to start the activity from Flutter View. So let's create a button to start the activity.
 RaisedButton(
              color: Colors.blue,
              onPressed: (){
                _startActivity();
              },
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text(
                  'Start Android Activity',
                  style: TextStyle(color: Colors.white,fontSize: 24),
                ),
              ),
            ),

Create the _startActivity()
Future<void> _startActivity() async {
    try {
      final String result = await platform.invokeMethod('StartSecondActivity');
      debugPrint('Result: $result ');
    } on PlatformException catch (e) {
      debugPrint("Error: '${e.message}'.");
    }
  }

So before that, we need to create the platform as well using the below code.
 static const platform = const MethodChannel('com.startActivity/testChannel');




Run and Test the App


Let's test the application. If you run it it will be like below.


Start Activity From Flutter View


Start Activity From Flutter View




Wrapping Up

This is just a very basic demo of how to call the platform-specific method, service or function from flutter view. In short, we can say that using this you can perform anything that you can do in normal android application written in Kotlin or Java.





Comments

  1. Could I get the sourcecode for this demo. I'm not sure where there Kotlin class goes.

    ReplyDelete
  2. Kotlin class goes inside the android folder for example: demo\android\app\src\main\kotlin\com\nplix\demo\MainActivity.kt where package name is com.nplix.demo.
    Its better to open the android directory as separate module for platform specific code.

    ReplyDelete
  3. However, I have updated the source code at https://github.com/debugandroid/flutter_android_activity_demo for reference.

    ReplyDelete
  4. You have shared a nice article here about the Flutter and Dart. Your article is very informative and useful for those who are looking for the best Dart Future Class Online. Thank you for sharing this article here.

    ReplyDelete

Post a Comment

Popular posts from this blog

Flutter Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use.



Create a flutter project



So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter.



Once your project is created you will get the default counter app and you try running the app in the…

Flutter State Management With Provider and ChangeNotifier

Flutter state management with provider library and why it's so important? There are lots of topics in flutter which are very important but out of those state management of your flutter application is the most important and little bit complicated as well. So in this article, I will try to explain how to use the provider package for managing the state of flutter and dart application and how to access the data down the hierarchy of the widget tree without recreating the whole UI.



Basic knowledge of the state management and data flow in the Flutter



Before starting the coding I would like to explain some basics about the Flutter application so that you can understand, why it's important to manage the state of your application in the correct way.



In Flutter, everything is a widget and whenever the state of your application changes the UI is recreated the UI with the new data. Let's list out the topic or problem that we are going to explore about state management.



Challenge of St…