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. Thanks for sharing the best information and suggestions, I love your content, and they are very nice and very useful to us. If you are looking for the best Flutter App Development, then visit Neebal. I appreciate the work you have put into this.

    ReplyDelete
  7. 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
  8. 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
  9. 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
  10. Thanks for Sharing..Keep Update…

    Web Hosting is the process of buying space for a website on the World Wide Web.
    Web Hosting Explained For Beginners
    Web Hosting

    ReplyDelete
  11. That's indeed a very detailed list of blog commenting websites.
    meal kit delivery services market

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

    ReplyDelete
  13. 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
  14. Great Article android based projects

    Java Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

    ReplyDelete
  15. 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
  16. Thanks for sharing this information ,i also have some information regarding the best flutter development company it will really helpful.

    ReplyDelete
  17. I had completely gothrow your post and it is full of innovative information.thanks for sharing this.
    Hire Java Developers

    ReplyDelete
  18. 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
  19. 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
  20. 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
  21. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Popular posts from this blog

WordPress Android App with REST API And Retrofit

Retrofit is the library which converts your JSON data into Java object. In this tutorial, we will learn about how to implement the Retrofit to create a WordPress Mobile App. As we all know, WordPress is the one of the biggest CMS (Content Management System) of the world. Wordpress full fill the requirements for all most every type of the website. So, in this tutorial, I am going to learn how to create an Android App using the WordPress REST API and Retrofit. What is Retrofit? If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps. Further, you can check the Retrofit Library here . So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website. Prerequisite for using the Retrofit for WordPress Android App Ther

How to Read and Write JSON data in Kotlin with GSON

Kotlin is now official language for Android development and it is well supported in Android Studio. So here in this tutorial, we are going to learn about how to read and write JSON data in Kotlin using GSON. If you would like to learn the java version of this tutorial check out the last tutorial " How to Read and Write JSON data using GSON ". Introduction In this tutorial, we will write two methods. In the first method, we will create a JSON file and in second method we will read the file and print in a text box.  If you like to know more about the basic entity of JSON you can check out Basic JSON entity here . What is JSON? JSON stands for J ava S cript O bject N otation JSON is a lightweight data-interchange format It is "self-describing" and easy to understand JSON is language independent and can we used in any language JSON Syntax Rules Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold