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
  5. Has compartido una tonelada de datos fundamentales en tu publicación. Es realmente esclarecedor y significativo. Sigue fortaleciendo nuestro discernimiento. Favorece tu corazón. desarrollador de aplicaciones

    ReplyDelete
  6. Flutter is becoming extremely popular and is exceedingly used in mobile application development. Find one of the best Flutter and Dart training in Chennai. Keep sharing these amazing tutorials.

    ReplyDelete
  7. Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you Best android app development company service provider.

    ReplyDelete
  8. I am very thankful to you that you have shared this information with us. I got some different kind of knowledge from your web page, and it is really helpful for everyone. Thanks for share it. AZWhatsApp APK 10.90 Free Download for Android

    ReplyDelete
  9. Very important blog, in case you want to Flutter app development Thanks for the blog. Will share it with peers and colleagues.

    ReplyDelete
  10. The article was up to the point and described the information about education and learning. Thanks to blog author for wonderful and informative post. Local AA Meetings

    ReplyDelete
  11. The information in the post you posted here is useful because it contains some of the best information available. Thanks for sharing it. Keep up the good work Application Development

    ReplyDelete
  12. Thanks for sharing this information ,i also have some information regarding the best flutter development company it will really helpful.

    ReplyDelete
  13. That is a fantastic blog post.. All the steps & tips you have specified in the above article are very informational and less time-consuming. This post will help even novices in instructing them from the beginning.

    Custom software application development chennai
    Web application development company in Chennai
    mobile app developers in chennai

    ReplyDelete
  14. The information you've provided is quite useful. It's incredibly instructional because it provides some of the most useful information. Thank you for sharing that. Mobile App Development Abu Dhabi

    ReplyDelete
  15. This information is very useful.
    To get more information about Video Analytics Solutions visit QuikieApps Video Analytics Solutions uses video surveillance systems to extract accessible, usable, and measurable information from live or stored video footage.

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. Nice and interesting information and informative too.
    App developers in India

    ReplyDelete
  19. This is a comprehensive guide for anyone who is looking to develop a Flutter app. You have done an excellent job of breaking down the process into easy-to-follow steps, making it a great resource for everyone specially beginners.
    Flutter App Development

    ReplyDelete
  20. I liked your way to represent such informative thoughts. Here you have shared an amazing article, this article provides a new idea about text detector. Thank you for sharing such informative thoughts.

    ReplyDelete

Post a Comment

Popular posts from this blog

Kotlin Parcelable Array Objects Send To Activity

We know that IPC (Inter Process Communication) between the activity is an extremely important part of any application development. We often required that we need to send some data to other activity. For example, we may be required to send an array of data, data could be an Integer, String, Long, Double, Float or any other custom data objects. So, In this example, we are going to learn how to implement the Kotlin Parcelable Array object to send the data from one activity to second activity. What is Parcel? The parcel class is designed as a high-performance IPC transport. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC, and references to live IBinde r objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel. Create Kotlin Parcelable Array Objects Parcelable is API for placing the arbitrary objects into the Parcel. In Actual in android app development, Parcelable is an interface

Create Custom EditText View in Android

We use the EditText for taking the input from the user and use it at several places in our project. We required to do lots of customization for each time and there are lots of redundant code we write. Writing and managing these redundant codes is very difficult for example if we want to change the look and feel of the view them we need to modify it at each place where our EditText is getting used. So to avoid these kinds of the problem we can create our own Custom EditText View by just. The EditText view is just an extension of the TextView with lots of editing option and properties that required for the user input. How To Create Custom EditText View For creating the Custom EditText we need to extend the AppCompatEditText and override all three constructors of the view as given below. import android.content.Context; import android.graphics.Typeface; import android.support.annotation.Nullable; import android.support.v7.widget.AppCompatEditText; import android.util.AttributeSet; public