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
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
ReplyDeleteVery 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
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
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.
ReplyDeleteFlutter App Development
Consider exploring effective solutions at Liberating Solution."
DeleteI 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.
ReplyDeleteTo 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.
ReplyDeleteMaximize 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.
ReplyDeleteTo 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.
ReplyDeleteJP 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.
ReplyDeleteLooking 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!
ReplyDeleteHire 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?
ReplyDeletePartnering 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.
ReplyDeleteAre 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.
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
ReplyDeleteAt 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
ReplyDeleteDevelopment Company
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!
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteTo 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.
ReplyDeleteOur 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