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
  21. To start an Android activity from a Flutter view, use platform channels. Define a method channel in Flutter and invoke it to trigger the activity on the native side. This approach seamlessly integrates Flutter with native Android functionality. For more on Flutter app development, explore various resources and tutorials.

    ReplyDelete
  22. Maximize your potential as a business with customized software development that is tailored to your specific requirements. Our experts are skilled in creating solutions that improve productivity and simplify the process. Custom software development provides adaptability, scalability and optimal performance, putting your business apart from competitors. Let us create the best solution to elevate your business up a notch with modern technology.

    ReplyDelete
  23. To start an Android activity from a Flutter view, you need to use platform channels to communicate between Flutter and native Android code. First, create a method channel in your Flutter app and invoke the method to start the activity. Then, implement the corresponding method in the Android part of your Flutter app to handle the activity start. This approach ensures seamless integration between Flutter and Android. As a leading Flutter App Development Company , we specialize in leveraging Flutter's capabilities to build high-performance, cross-platform apps, providing users with smooth and responsive experiences across devices.

    ReplyDelete
  24. JP Loft is a trusted ICO Development Company offering end-to-end solutions for launching successful ICOs. From token creation to smart contract development, their expert team ensures a smooth and secure process for startups and enterprises alike. With a focus on transparency and efficiency, JP Loft delivers tailored ICO services that cater to various industry needs, helping businesses raise funds and achieve their blockchain goals effectively.

    ReplyDelete
  25. Looking to enhance your online presence? hire-web-developers from JPLoft is the way to go! Their skilled team specializes in creating customized, efficient websites tailored to your business needs. With flexible hiring models and a strong commitment to quality, JPLoft ensures your project runs smoothly from start to finish. Plus, their extensive experience across various industries guarantees innovative solutions. Don’t miss out on the opportunity to boost your business’s efficiency—partner with JPLoft today!

    ReplyDelete
  26. Hire iOS Developers from JPLoft sounds like a fantastic opportunity! With a team that is both trained and certified, you can expect high-quality, custom iOS apps tailored to your needs. Whether you’re looking to build a feature-rich app from the ground up, enhance an existing one, or ensure ongoing maintenance and support, their expertise can make a significant difference. Investing in skilled developers is key to creating a seamless user experience and staying competitive in the app market. Have you had any experience working with dedicated iOS developers before?

    ReplyDelete
  27. Partnering with ourHire iOS Developers can undoubtedly expand your business's possibilities. By utilizing our carefully selected iOS developers' skills, you can create future-oriented apps easy to use, with a balance of visual appeal and optimal functionality.

    Are you searching for iOS application developers to transform your idea into a reality? Don't look any further! With a track record of successfully executing projects across various sectors, JPLoft provides seamless services from ideation to application launch.

    ReplyDelete
  28. This article provides a clear guide on integrating Android activities within a Flutter app. It outlines project setup, creating a new activity, managing dependencies, and establishing communication via a MethodChannel. The emphasis on themes and configurations ensures a smooth user experience while maintaining platform-specific functionality. Great resource for developers! https://www.jploft.com/ewallet-app-development

    ReplyDelete
  29. At JPLoft Solutions, we specialize in cutting-edge fantasy football app development that elevates the gaming experience for enthusiasts. Our expert team crafts user-friendly applications featuring real-time scoring, customizable leagues, and advanced player analytics. With social connectivity, robust league management tools, and seamless data integration, our fantasy football app development services ensure users enjoy a thrilling and immersive experience. Partner with us to transform your fantasy football vision into reality Fantasy Football App
    Development Company

    ReplyDelete
  30. Great guide on starting an Android activity from a Flutter view! This integration is crucial for seamless native functionality within Flutter apps. For businesses looking to implement this efficiently, it's smart to hire Flutter app developers who can ensure smooth cross-platform performance and deep native integration. Keep sharing such insights!

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

    ReplyDelete
  32. To implement Android native features in a Flutter app, developers can utilize platform channels to start an Android activity from a Flutter view. This allows seamless integration of native Android code with Flutter's UI. For expert assistance in achieving this, consider Hire Flutter App Developers for professional development solutions.

    ReplyDelete
  33. Our NodeJS development services deliver scalable, high-performance solutions tailored to your business needs. From API development to real-time applications, we specialize in building efficient, server-side applications using the latest Node.js frameworks and tools. Trust our expertise for fast, secure, and robust development that empowers your web and mobile applications to excel.

    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 ...

Scan and List All Available WiFi Network In Android

In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. You May Like Below Topic: How to Read and Write JSON data using GSON WP Android App using REST and volley WP Android App using REST and volley part2 Implementation of SwipeRefreshLayout in RecyclerView Create Amazing Bottom Navigation Bar Without Any External Library Introduction In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. We will add this functionality to our existing Demo app " Video Gallery ". If you would like to check out t...