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
- From File menu select the New Flutter Project
- Enter the project name
- Select the AndroidX support and click on next
- After the above, we step click on Finish We will have the following project structure created.
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.
Create the Activity
Just right-clickon 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.


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.- Check out getting started with flutter.
- Check Flutter.dev
Could I get the sourcecode for this demo. I'm not sure where there Kotlin class goes.
ReplyDeleteKotlin 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.
ReplyDeleteIts better to open the android directory as separate module for platform specific code.
However, I have updated the source code at https://github.com/debugandroid/flutter_android_activity_demo for reference.
ReplyDeleteYou 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.
ReplyDeleteasd
ReplyDeleteHas 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
ReplyDeleteThanks 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.
ReplyDeleteFlutter 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.
ReplyDeleteHey 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.
ReplyDeleteI 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
ReplyDeleteWonderful Post!!! Thanks for sharing this great blog with us.
ReplyDeleteAndroid Course in Chennai
Android Online Course
Android Course in Coimbatore
Very important blog, in case you want to Flutter app development Thanks for the blog. Will share it with peers and colleagues.
ReplyDeleteThe 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
ReplyDeleteGreat blog with good information.
ReplyDeleteGoogle Flutter and Dart Online Training
Google flutter training in chennai
Flutter training in Bangalore
Great Article android based projects
ReplyDeleteJava 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
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
ReplyDeleteThanks for sharing this information ,i also have some information regarding the best flutter development company it will really helpful.
ReplyDeleteThat 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.
ReplyDeleteCustom software application development chennai
Web application development company in Chennai
mobile app developers in chennai
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
ReplyDeleteThis information is very useful.
ReplyDeleteTo 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.
ReplyDeleteInformative content, thanks for sharing this article.
Why You Choose Flutter
Why You Choose Flutter for your Project
This comment has been removed by the author.
ReplyDeleteGreat blog with good information.
ReplyDeleteR Programming Training in Chennai
R Programming Online Course
R Programming Training in Bangalore
This comment has been removed by the author.
ReplyDeleteNice and interesting information and informative too.
ReplyDeleteApp developers in India