Google search engine
Home Blog Page 74

Flutter — Email Launcher

0

In this article, we will explore the Flutter — Email Launcher. We see how to execute a demo program. We will tell you the best way to open the default email application with email ID, body, and subject utilizing the url_launcher package, and how to work it in your Flutter applications.

  • For URL Launcher:

url_launcher | Flutter Package
Flutter plugin for launching a URL. Supports web, phone, SMS, and email schemes.pub.dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion


Introduction:

The below demo video shows how to open Email Launcher in Flutter and how Email Launcher will work using the url_launcher plugin in your Flutter applications. We will show you how to open default email applications with email ID, body, and subject. when the user taps on the button, then they will navigate to the default email app with email ID, body, and subject. It will be shown on your device.

Demo Module::


Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
url_launcher: ^6.2.2

Step 2: Import

import 'package:url_launcher/url_launcher.dart';

Step 3: Run flutter packages get in the root directory of your app.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

In the main .dart file. We will create a new class MyHomePage(). In this class, we will add the Center widget in the body part. In this widget, we will add a Column widget with mainAxisAlignment as the center.

Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(
'assets/logo.png',
height: heightSize * 0.15,
),
SizedBox(
height: heightSize * 0.15,
),
ElevatedButton(
onPressed: () => _email(),
style: ElevatedButton.styleFrom(
padding: EdgeInsets.only(
left: widthSize * 0.1, right: widthSize * 0.1),
textStyle:
const TextStyle(fontSize: 19, fontStyle: FontStyle.normal),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(30))),
),
child: const Text('Send Email'),
),
],
),
),

Inside the column, we will add an image with height and ElevatedButton().In this button, we will add the onPressed function. In this function, we will navigate the _email() method. This method we will define below with code. Also, we will add style and its child we will add ‘Send Email’ text.

When we run the application, we ought to get the screen’s output like the underneath screen capture.
Output

Now, we will define _email() method:

In this method, when users press the button then they will open the default mobile email applications. In this method, we will declare an async and add three Strings email, subject, and body.

void _email() async {
String email = Uri.encodeComponent("test@aeologic.com");
String subject = Uri.encodeComponent("Hello Flutter Dev's");
String body = Uri.encodeComponent(
"Hi! I'm Flutter Developer. This is a Email launcher demo testing.");
if (kDebugMode) {
print(subject);
print(email);
print(body);
}
var url = Uri.parse("mailto:$email?subject=$subject&body=$body");
if (await canLaunchUrl(url)) {
await launchUrl(url);
} else {
throw 'Could not launch $url';
}
}

The fundamental email ID, subject, and body are assigned as a string to the “url” variable. The application is told to send off the mobile’s default mailing application by the grammar “mailto:”. After that enter the email id, subject, and body determined in the “url” variable in the “To”, “Body”, and “Subject” areas. To guarantee that the variable is never changed, it is pronounced as a “const.”

The URL is possibly launched assuming it is feasible to do as such, in which case it is called by passing the URL variable. Also a contention to the launch() capability. Otherwise, it will throw/print a message with the url value, as an error message.

When we run the application, we ought to get the screen’s output like the underneath screen capture.
Output

Code File:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_email_launcher_demo/splash_screen.dart';
import 'package:url_launcher/url_launcher.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
debugShowCheckedModeBanner: false,
home: const Splash(),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
void _email() async {
String email = Uri.encodeComponent("test@aeologic.com");
String subject = Uri.encodeComponent("Hello Flutter Dev's");
String body = Uri.encodeComponent(
"Hi! I'm Flutter Developer. This is a Email launcher demo testing.");
if (kDebugMode) {
print(subject);
print(email);
print(body);
}
var url = Uri.parse("mailto:$email?subject=$subject&body=$body");
if (await canLaunchUrl(url)) {
await launchUrl(url);
} else {
throw 'Could not launch $url';
}
}

@override
Widget build(BuildContext context) {
var heightSize = MediaQuery.of(context).size.height;
var widthSize = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
centerTitle: true,
automaticallyImplyLeading: false,
title: Text(
widget.title,
style: const TextStyle(fontSize: 20),
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(
'assets/logo.png',
height: heightSize * 0.15,
),
SizedBox(
height: heightSize * 0.15,
),
ElevatedButton(
onPressed: () => _email(),
style: ElevatedButton.styleFrom(
padding: EdgeInsets.only(
left: widthSize * 0.1, right: widthSize * 0.1),
textStyle:
const TextStyle(fontSize: 19, fontStyle: FontStyle.normal),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(30))),
),
child: const Text('Send Email'),
),
],
),
),
);
}
}

Conclusion:

In the article, I have explained the Email Launcher in Flutter; you can modify this code according to your choice. This was a small introduction to the Email Launcher in Flutter User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying Email Launcher in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on Email Launcher using the url_launcher plugin in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Exploring Event and Method Channels in Flutter: A Comprehensive Guide


Flutter, the powerful toolkit from Google, seamlessly blends Dart and native code. Let’s dive into the essential communication tools it offers: Event Channels and Method Channels. This guide aims to simplify it, breaking down what these channels do, and their benefits, and even revealing a nifty trick to bypass using a device_info plugin with Event Channels.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Contents:

Event Channel

Method Channel

Decoding Bidirectional Interaction

Scenarios to use Event Channels

Scenarios to use Method Channels

A Practical Demonstration

Showcasing with a Live Demo

Conclusion

Github

Reference


Event Channel:

Bridging the Gap in Real-Time Communication

Event Channels in Flutter are a powerful mechanism for real-time communication between Dart and native code. They are particularly useful for scenarios where continuous streams of data need to be shared. Let’s break down the key aspects of Event Channels:

  • Pros:
  1. Real-time Updates: Event Channels facilitate the continuous flow of data from native code to Dart, ensuring that your Flutter UI remains up-to-date with the latest information.
  2. Bi-Directional Communication: Events can flow in both directions, allowing communication from Dart to native code and vice versa.
  • Cons:
  1. Complexity: Implementing and managing Event Channels can be more complex than other communication methods, especially for beginners.
  2. Overhead: Continuous communication might introduce some performance overhead, so it’s crucial to optimize for efficiency.

Differences from Method Channels:

  1. Continuous Streams: While Method Channels are designed for single invocations, Event Channels are suitable for continuous data streams.
  2. Bi-Directional Communication: Event Channels are more suited for scenarios where both Dart and native code need to send updates back and forth continuously.

Method Channel:

Precise and Controlled Communication

Method Channels provide a straightforward way to call native methods from Dart code and receive the results. This one-time communication is beneficial for scenarios where a single piece of data or action needs to be conveyed. Let’s explore the key aspects of Method Channels:

  • Pros:
  1. Simplicity: Method Channels offer a simpler and more controlled approach compared to Event Channels, making them suitable for one-off interactions.
  2. Efficiency: The overhead is lower compared to Event Channels, making Method Channels more efficient for singular data transfers.
  • Cons:
  1. Limited Real-Time Updates: If real-time updates are needed, Event Channels might be a more suitable choice.
  2. Complexity for Continuous Streams: Implementing continuous data streams with Method Channels can be less intuitive and might require additional workarounds.

Differences from Event Channels:

  1. Single Invocation: Method Channels are designed for single method invocations and are ideal for scenarios where a specific action needs to be performed.
  2. One-Way Communication: While Event Channels support bi-directional communication, Method Channels follow a one-way communication pattern.

Decoding Bidirectional Interaction:

Both Event Channels and Method Channels in Flutter support bidirectional communication, but they are often used in different scenarios. Event Channels excel in continuous streams of data, providing real-time updates in both directions. On the other hand, Method Channels are more suited for one-time method invocations, even though they can be used bidirectionally by handling multiple method calls independently.


Scenarios to use Event Channels

  1. Custom Hardware Integration:

Scenario: You’re working with a specific hardware component for which there is no existing Flutter plugin.

Reason to Use Event Channel: Event Channels allow you to establish a continuous communication stream between Dart and native code, making it suitable for scenarios where you need real-time updates from custom hardware.

2. Low Dependency Footprint:

Scenario: You want to minimize the number of external dependencies in your Flutter project.

Reason to Use Event Channel: By using Event Channels, you can reduce your reliance on third-party plugins, keeping your project lightweight and giving you more control over the codebase.

3. Real-Time Data Streams:

Scenario: Your application requires real-time updates from the native side, and existing plugins do not provide the necessary continuous data stream.

Reason to Use Event Channel: Event Channels are designed for scenarios where you need continuous streams of data. If the existing plugins don’t support real-time updates, Event Channels offer a customizable solution.

4. Performance Optimization:

Scenario: You are working on a performance-critical application, and existing plugins introduce unnecessary overhead.

Reason to Use Event Channel: Event Channels allow you to optimize performance by tailoring the communication process to your specific needs, avoiding any unnecessary abstraction layers that might be present in plugins.

5. Integration with Proprietary Systems:

cenario: Your Flutter app needs to integrate with a proprietary or specialized system that lacks community-supported plugins.

Reason to Use Event Channel: Event Channels provide a flexible way to communicate with native code, allowing you to integrate with proprietary systems for which no public plugins are available.

6. Custom UI Components:

Scenario: You’re building custom UI components that require continuous updates or complex interactions.

Reason to Use Event Channel: Event Channels offer the flexibility to send and receive data between Dart and native code in real-time, making them suitable for scenarios where custom UI components demand dynamic updates.

Remember that while Event Channels provide flexibility and control, they also come with added responsibility for managing the communication protocol and ensuring efficient data transfer between Dart and native code. Carefully assess your project requirements and consider the trade-offs before opting for Event Channels over existing plugins.


Scenarios to use Method Channels:

1. Custom Functionality:

Scenario: You need to implement specific functionalities that are not covered by existing Flutter plugins.

Reason to Use Method Channel: Method Channels allow you to define custom methods in native code and invoke them from Dart. This is useful when you need to implement tailored functionality that doesn’t fit within the scope of existing plugins.

2. Direct Native API Access:

Scenario: You require direct access to native APIs without relying on the abstractions provided by plugins.

Reason to Use Method Channel: Method Channels enable direct communication between Dart and native code, allowing you to call native methods and access APIs without the additional layer of abstraction introduced by plugins.

3. Performance Optimization:

Scenario: Your application demands optimal performance, and existing plugins introduce unnecessary overhead.

Reason to Use Method Channel: By using Method Channels, you have more control over the communication process, enabling you to fine-tune performance and avoid any performance bottlenecks introduced by generic plugins.

4. Integration with Native Libraries:

Scenario: Your project requires integration with native libraries that are not covered by existing plugins.

Reason to Use Method Channel: Method Channels provide a way to bridge the gap between Flutter and native code, allowing you to directly interface with native libraries that may not have dedicated Flutter plugins.

5. Legacy System Integration:

Scenario: You need to integrate with a legacy system or a platform that lacks community-supported plugins.

Reason to Use Method Channel: Method Channels offer a direct and customizable communication bridge, making them suitable for integrating with legacy systems or platforms for which no suitable plugins are available.

6. Complex Business Logic:

Scenario: Your application involves complex business logic that is better handled in native code.

Reason to Use Method Channel: Method Channels enable you to encapsulate and execute complex business logic on the native side, providing a more efficient and tailored solution compared to generic plugins.

7. Specific UI Implementations:

Scenario: You are implementing custom UI components with complex interactions that aren’t supported by existing plugins.

Reason to Use Method Channel: Method Channels offer the flexibility to trigger specific UI interactions or behaviors directly from Dart, allowing you to implement custom UI components with the desired native behavior.

When choosing between Method Channels and plugins, carefully evaluate the project requirements, considering factors such as performance, customizability, and the availability of existing solutions. Method Channels provide a powerful way to establish communication between Flutter and native code, giving you the flexibility to implement features that may not be covered by standard plugins.


A Practical Demonstration:

Avoiding Plugin Dependency with Event Channels:

As a Flutter developer, you might want to reduce your reliance on plugins, and Event Channels provide an elegant solution for scenarios like retrieving device information. This approach helps maintain greater control over the codebase and can lead to a more lightweight application. I also set up an Event Channel for sending a string to Flutter

Add code in MainActivity.kt

class MainActivity : FlutterActivity() {
private val handler = Handler(Looper.getMainLooper())

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

// Set up an EventChannel for device information
val deviceEventChannel = EventChannel(
flutterEngine?.dartExecutor?.binaryMessenger,
DEVICE_EVENT_CHANNEL_NAME
)

// Send device information to Flutter
handler.postDelayed({
val deviceInfo = getDeviceInfo()
deviceEventChannel.setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, eventSink: EventChannel.EventSink) {
eventSink.success(deviceInfo)
}

override fun onCancel(arguments: Any?) {
// Handle cancellation
}
})
}, 1000)

// Set up an EventChannel for sending a string to Flutter
val stringEventChannel = EventChannel(
flutterEngine?.dartExecutor?.binaryMessenger,
STRING_EVENT_CHANNEL_NAME
)

// Example: send a string from native to Flutter every 2 seconds
handler.postDelayed({
sendStringToFlutter("Hello from native!")
// You can change the string or the frequency as needed
}, 2000)
}

private fun getDeviceInfo(): Map<String, Any> {
val deviceInfo = HashMap<String, Any>()
deviceInfo["model"] = Build.MODEL
deviceInfo["brand"] = Build.BRAND
deviceInfo["version"] = Build.VERSION.RELEASE
// Add more information as needed

return deviceInfo
}

private fun sendStringToFlutter(message: String) {
val stringEventChannel = EventChannel(
flutterEngine?.dartExecutor?.binaryMessenger,
STRING_EVENT_CHANNEL_NAME
)
stringEventChannel.setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, eventSink: EventChannel.EventSink) {
eventSink.success(message)
}

override fun onCancel(arguments: Any?) {
// Handle cancellation
}
})
}

companion object {
private const val DEVICE_EVENT_CHANNEL_NAME = "deviceEventChannel"
private const val STRING_EVENT_CHANNEL_NAME = "stringEventChannel"
}

}

Call Event Channel in Ui

import 'package:event_channel_demo/core/constants/icon_constants.dart';
import 'package:event_channel_demo/core/constants/string_constants.dart';
import 'package:event_channel_demo/core/custom_elevated_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class EventChannelView extends StatefulWidget {
const EventChannelView({super.key});

@override
State<EventChannelView> createState() => _EventChannelViewState();
}

class _EventChannelViewState extends State<EventChannelView> {

static const EventChannel _deviceEventChannel =
EventChannel('deviceEventChannel');
static const EventChannel _stringEventChannel =
EventChannel('stringEventChannel');

Map<String, dynamic>? _deviceInfo;
String _stringFromNative = StringConstants.notReceivedString;

void _stopListeningAndClearEventChannelData() {
setState(() {
_deviceInfo = null;
_stringFromNative = StringConstants.notReceivedString;
});
}

void _sendDeviceInfoEvent() {
_deviceEventChannel.receiveBroadcastStream().listen((dynamic event) {
setState(() {
_deviceInfo = Map<String, dynamic>.from(event);
});
});
}

void _sendStringEvent() {
_stringEventChannel.receiveBroadcastStream().listen((dynamic event) {
setState(() {
_stringFromNative = event.toString();
});
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
title: Text(StringConstants.eventChannel),
),
body: Column(
// mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
height: 100,
width: 100,
margin: const EdgeInsets.all(12),
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage(AppIcons.bgImage),
alignment: Alignment.center,
fit: BoxFit.fill)),
)
],
),
SizedBox(height: MediaQuery.of(context).size.height*0.12),
if (_deviceInfo != null)
for (var entry in _deviceInfo!.entries)
Text(
'${entry.key}: ${entry.value}',
style: const TextStyle(fontSize: 16),
),
Text(
'${StringConstants.stringFromNative}: $_stringFromNative',
style: const TextStyle(fontSize: 16),
),
const SizedBox(height: 20),
CustomElevatedButton(title: StringConstants.getDeviceInfoNative,
onTap: _sendDeviceInfoEvent
),
const SizedBox(height: 10),
CustomElevatedButton(title: StringConstants.getStringNative,
onTap: _sendStringEvent
),
const SizedBox(height: 10),
CustomElevatedButton(title: StringConstants.clearData,
onTap: _stopListeningAndClearEventChannelData
),

],
),
);
}
}

Calculating the Sum with Method Channel:

To further showcase the usage of Method Channels, we’ve implemented a simple demo where Dart calls a native method to calculate the sum of two numbers. This provides a practical example of how Method Channels can be employed for specific tasks.

class MainActivity : FlutterActivity() {
private val handler = Handler(Looper.getMainLooper())
private val CHANNEL = "exampleMethodChannel"

override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)

MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
when (call.method) {
"getMessage" -> result.success("Hello from Android!")
"calculateSum" -> {
val a = call.argument<Int>("a") ?: 0
val b = call.argument<Int>("b") ?: 0
val sum = calculateSum(a, b)
result.success(sum)
}
else -> result.notImplemented()
}
}
}

private fun calculateSum(a: Int, b: Int): Int {
return a + b
}
}

Call Method Channel in Ui

import 'package:event_channel_demo/core/constants/icon_constants.dart';
import 'package:event_channel_demo/core/constants/string_constants.dart';
import 'package:event_channel_demo/core/custom_elevated_button.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class MethodChannelView extends StatefulWidget {
const MethodChannelView({super.key});

@override
State<MethodChannelView> createState() => _MethodChannelViewState();
}

class _MethodChannelViewState extends State<MethodChannelView> {
static const MethodChannel _methodChannel =
MethodChannel('exampleMethodChannel');

int _result = 0;

Future<void> _calculateSum(int a, int b) async {
try {
final dynamic result = await _methodChannel
.invokeMethod('calculateSum', {'a': a, 'b': b});
setState(() {
_result = result as int;
});
} on PlatformException catch (e) {
setState(() {
_result = 0;
});
if (kDebugMode) {
print('Error: ${e.message}');
}
}
}
void _stopListeningAndClearMethodChannelData() {
setState(() {
_result = 0;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
title: Text(StringConstants.methodChannel),
),
body: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
height: 100,
width: 100,
margin: const EdgeInsets.all(12),
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage(AppIcons.bgImage),
alignment: Alignment.center,
fit: BoxFit.fill)),
)
],
),
SizedBox(height: MediaQuery.of(context).size.height*0.15),
Text(
'${StringConstants.result}: $_result',
style: const TextStyle(fontSize: 16),
),
const SizedBox(height: 10),
CustomElevatedButton(title: '${StringConstants.calculateSum} (10 + 20)',
onTap: () => _calculateSum(10, 20),
),
const SizedBox(height: 10),
CustomElevatedButton(title: '${StringConstants.calculateSum} (5 + 7)',
onTap: () => _calculateSum(5, 7),
),
const SizedBox(height: 10),
CustomElevatedButton(title: StringConstants.clearData,
onTap: _stopListeningAndClearMethodChannelData,
),
],
),
);
}
}


Showcasing with a Live Demo

Event Channel and Method Channel in Action

Conclusion:

Choosing the Right Channel for the Job

In conclusion, both Event and Method Channels play crucial roles in Flutter development, offering versatile solutions for communication between Dart and native code. The choice between them depends on the specific requirements of your application.

When dealing with real-time updates or continuous data streams, Event Channels shine. For controlled and one-time interactions, Method Channels provide a simpler and more efficient solution.

By understanding the strengths and weaknesses of each channel, Flutter developers can make informed decisions, ensuring the seamless integration of their applications with native code. Happy coding!


Github:

Explore the entire codebase for this demonstration through the provided link

GitHub – RitutoshAeologic/event_method_channel_demo
Contribute to RitutoshAeologic/event_method_channel_demo development by creating an account on GitHub.github.com


❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Reference:

Writing custom platform-specific code
Learn how to write custom platform-specific code in your app.docs.flutter.dev


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project hourly or full-time as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Polylines On Google Maps In Flutter

0

Flutter, the open-source UI software development toolkit, has acquired enormous prominence for its adaptability and convenience. While fostering an application with flutter that requires map functionalities, one of the fundamental highlights is the capacity to show polyline points. This polyline points to a line or path on a map, for example, those you would find in Google Maps.

In this article, we will explore the Polylines On Google Maps in Flutter. We see how to execute a demo program. We will tell you the best way how to draw polylines on Google Maps to show the path, lines, directions, etc in your Flutter applications.

  • For Google Maps Flutter:

google_maps_flutter | Flutter Package
A Flutter plugin for integrating Google Maps in iOS and Android applications.pub.dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Constructor

Properties

Implementation

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to draw Polylines On Google Maps in Flutter and how Polylines will work on Google Maps in your Flutter applications. We will draw polylines to show you ways, directions, or trails with various types of colors or lines on Google Maps. It will be shown on your device.

Demo Module::


Constructor:

To utilize Polyline, you need to call the constructor underneath:

const Polyline({
required this.polylineId,
this.consumeTapEvents = false,
this.color = Colors.black,
this.endCap = Cap.buttCap,
this.geodesic = false,
this.jointType = JointType.mitered,
this.points = const <LatLng>[],
this.patterns = const <PatternItem>[],
this.startCap = Cap.buttCap,
this.visible = true,
this.width = 10,
this.zIndex = 0,
this.onTap,
});

Properties:

There are some properties of Polyline:

  • > PolylineId — This property is used to uniquely identify a Polyline among GoogleMap polylines. This does not have to be globally unique, or unique among the list.
  • > consumeTapEvents — This property is used to True if the Polyline consumes tap events. If this is false, the onTap callback will not be triggered.
  • > Color — This property is utilized for the Line segment color in ARGB design, a similar configuration utilized by Color. The default value is black (0xff000000.
  • > endCap — This property is utilized for the cap at the end vertex of the polyline. The default end cap is ButtCap. Supported on Android only.
  • > visible — This property is utilized for True if the marker is visible.
  • > width — This property is utilized to define the width of the line segment to be drawn. The width is constant and independent of the camera’s zoom level. The default value is 10.
  • > points — This property is utilized for the vertices of the polyline to be drawn.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
google_maps_flutter: ^2.5.2

Step 2: Import

import 'package:google_maps_flutter/google_maps_flutter.dart';

Step 3: Run flutter packages get in the root directory of your app.

Step 4: Update the build.gradle File

Set the minSdkVersion in android/app/build.gradle:

android {
defaultConfig {
minSdkVersion 20
}
}

Step 5: Add API Key

  • For Andriod:

Add the Api key in android/app/src/main/AndroidManifest.xml:

<manifest ...
<application ...
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY_HERE"/>
</application>
</manifest>
  • For Ios:

To set up, specify your API key in the application delegate ios/Runner/AppDelegate.m:

import GoogleMaps
...
GMSServices.provideAPIKey("YOUR_API_KEY_HERE")

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

In the main .dart file. We will create a new class MyHomePage(). In this class, we will define a GoogleMapControlle:r as a mapController variable and Set Polylines as a polylines variable ie equal to a curly bracket.

GoogleMapController? mapController;
Set<Polyline> polylines = {};

Now, we will define three latitude and longitude joints where three lines will be drawn:

LatLng location1 = const LatLng(28.612898, 77.365930);
LatLng location2 = const LatLng(28.5897989, 77.3368915);
LatLng location3 = const LatLng(28.6029172, 77.3195082);

We will create an initState() method. In this method, we will add the polylinesDraw() method. We will define the below code.

@override
void initState() {
polylinesDraw();
super.initState();
}

We will define polylinesDraw() method are:

In this method, we will add three polylines with PolylineId, points, and different colors. We will add a polyline to the variable.

polylinesDraw() async {
polylines.add(Polyline(
polylineId: PolylineId(location1.toString()),
visible: true,
width: 5,
points: [
location1,
location2,
],
color: Colors.pink,
));
polylines.add(Polyline(
polylineId: PolylineId(location1.toString()),
visible: true,
width: 5,
points: [
location2,
location3,
],
color: Colors.deepPurple,
));

polylines.add(Polyline(
polylineId: PolylineId(location1.toString()),
visible: true,
width: 5,
points: [
location3,
location1,
],
color: Colors.red,
));

setState(() {
});
}

In the body part, we will add the GoogleMap() method. In this method, we will add zoomGesturesEnabled was true, set the initialCameraPosition as zoom is 14, and the target was your location wrap to CameraPosition(), add variable on polylines, map type was normal, onMapCreated was this method called when map is created. Inside onMapCreated, we will add the setState() function. In this function, we will add mapController is equal to the controller.

GoogleMap(
zoomGesturesEnabled: true,
initialCameraPosition: CameraPosition(
target: location1,
zoom: 14.0,
),
polylines: polylines,
mapType: MapType.normal,
onMapCreated: (controller) {
//method called when map is created
setState(() {
mapController = controller;
});
},
)
When we run the application, we ought to get the screen’s output like the underneath screen capture.
Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:poly/splash_screen.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Splash(),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
GoogleMapController? mapController;
Set<Polyline> polylines = {};

LatLng location1 = const LatLng(28.612898, 77.365930);
LatLng location2 = const LatLng(28.5897989, 77.3368915);
LatLng location3 = const LatLng(28.6029172, 77.3195082);

@override
void initState() {
polylinesDraw();
super.initState();
}

polylinesDraw() async {
polylines.add(Polyline(
polylineId: PolylineId(location1.toString()),
visible: true,
width: 5,
points: [
location1,
location2,
],
color: Colors.pink,
));

polylines.add(Polyline(
polylineId: PolylineId(location1.toString()),
visible: true,
width: 5,
points: [
location2,
location3,
],
color: Colors.deepPurple,
));

polylines.add(Polyline(
polylineId: PolylineId(location1.toString()),
visible: true,
width: 5,
points: [
location3,
location1,
],
color: Colors.red,
));

setState(() {
//refresh UI
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text("Flutter Polylines on Google Map Demo"),
backgroundColor: Colors.purpleAccent,
),
body: GoogleMap(
zoomGesturesEnabled: true,
initialCameraPosition: CameraPosition(
target: location1,
zoom: 14.0,
),
polylines: polylines,
mapType: MapType.normal,
onMapCreated: (controller) {
setState(() {
mapController = controller;
});
},
));
}
}

Conclusion:

In the article, I have explained the Polylines On Google Maps in Flutter; you can modify this code according to your choice. This was a small introduction to the Polylines On Google Maps in Flutter User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying Polylines On Google Maps in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on Polylines On Google Maps to show paths, lines, or directions with different colors in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Hyperlinks In Flutter

0

As hyperlinks are a fundamental piece of the web stage, this is one of the main things you figure out how to carry out as a developer and to utilize as a user. Flutter being a UI structure is less associated with hyperlinks. Beyond web sees.

In this article, we will explore the Hyperlinks In Flutter. We see how to execute a demo program. We will tell you the two best ways to create hyperlinks utilizing the url_launcher package, and flutter_inappwebview package, and how to work it in your Flutter applications.

  • For URL Launcher:

url_launcher | Flutter Package
Flutter plugin for launching a URL. Supports web, phone, SMS, and email schemes.pub.dev

  • For Flutter InAppWebView:

flutter_inappwebview 5.8.0 | Flutter Package
A Flutter plugin allows you to add an inline webview, use a headless webview, and open an in-app browser…pub.dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to create hyperlinks in Flutter and how hyperlinks will work using the url_launcher plugin and flutter_inappwebview plugin in your Flutter applications. We will show you how to create and open a link. We will create two methods, first open the link on the web browser using the url_launcher plugin, and second open the link on the bottom sheet using the flutter_inappwebview plugin. It will be shown on your device.

Demo Module::


Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
url_launcher: ^6.2.3
flutter_inappwebview: ^5.8.0

Step 2: Import

import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Step 3: Run flutter packages get in the root directory of your app.

Step 4: For the Url launcher

Add the <queries> in android/app/src/main/AndroidManifest.xml:

<queries>
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="https" />
</intent>
</queries>

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

In the main .dart file. We will create a new class MyHomePage(). In this class, we will add the Column widget on the body part. In this widget, we will add an image and two elevated buttons. The first button was to open a link on a web browser and the other was to open a link on a ModalBottomSheet. We will define both buttons below.

Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(
'assets/logo.png',
height: heightSize * 0.15,
),
SizedBox(
height: heightSize * 0.08,
),
ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
padding: EdgeInsets.only(
left: widthSize * 0.1, right: widthSize * 0.1),
textStyle:
const TextStyle(fontSize: 19, fontStyle: FontStyle.normal),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(30))),
),
child: const Text('Open in Browser'),
),
SizedBox(
height: heightSize * 0.05,
),
ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
padding: EdgeInsets.only(
left: widthSize * 0.1, right: widthSize * 0.1),
textStyle:
const TextStyle(fontSize: 19, fontStyle: FontStyle.normal),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(30))),
),
child: const Text('Open in ModalBottomSheet'),
),
],
),
When we run the application, we ought to get the screen’s output like the underneath screen capture.
Output

Now, we will define Open in Browser Button:

In this button, when the user taps the button, then the link opens on a default web browser using the url_launcher plugin. This button navigates a launchUrlString (‘https://flutterdevs.com/’) on the onPressed function.onPressed: () => launchUrlString(‘https://flutterdevs.com/’),

When we run the application, we ought to get the screen’s output like the underneath screen capture.
Output

Now, we will define Open in ModalBottomSheet Button:

In this button, when the user taps the button, then the link opens on a bottom sheet using the flutter_inappwebview plugin. This button navigates a showModalBottomSheet() method on the onPressed function.

 onPressed: () => showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(20),
),
),
clipBehavior: Clip.antiAliasWithSaveLayer,
builder: (BuildContext context) {
return InAppWebView(
initialUrlRequest: URLRequest(
url: Uri.parse('https://flutterdevs.com/'),
),
);
},
),

In the showModalBottomSheet() method, we will add context, shape, clipBehavior, and builder. Inside the builder, we will return an InAppWebView() method. In this method, we will add our URL.

When we run the application, we ought to get the screen’s output like the underneath screen capture.
Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_hyperlink_demo/splash_screen.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher_string.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
useMaterial3: true,
),
home: const Splash(),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
var heightSize = MediaQuery.of(context).size.height;
var widthSize = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(
'assets/logo.png',
height: heightSize * 0.15,
),
SizedBox(
height: heightSize * 0.08,
),
ElevatedButton(
onPressed: () => launchUrlString('https://flutterdevs.com/'),
style: ElevatedButton.styleFrom(
padding: EdgeInsets.only(
left: widthSize * 0.1, right: widthSize * 0.1),
textStyle:
const TextStyle(fontSize: 19, fontStyle: FontStyle.normal),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(30))),
),
child: const Text('Open in Browser'),
),
SizedBox(
height: heightSize * 0.05,
),
ElevatedButton(
onPressed: () => showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(20),
),
),
clipBehavior: Clip.antiAliasWithSaveLayer,

builder: (BuildContext context) {
return InAppWebView(
initialUrlRequest: URLRequest(
url: Uri.parse('https://flutterdevs.com/'),
),
);
},
),
style: ElevatedButton.styleFrom(
padding: EdgeInsets.only(
left: widthSize * 0.1, right: widthSize * 0.1),
textStyle:
const TextStyle(fontSize: 19, fontStyle: FontStyle.normal),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(30))),
),
child: const Text('Open in ModalBottomSheet'),
),
],
),
),
);
}
}


Conclusion:

In the article, I have explained the Hyperlinks in Flutter; you can modify this code according to your choice. This was a small introduction to the Hyperlinks in Flutter User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying Hyperlinks in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on Hyperlinks using the url_launcher plugin and flutter_inappwebview pugin in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Explore Focused Pop-Up Menu In Flutter

0

An adaptable and easy-to-use component of Flutter is the popup menu Flutter, which offers a functional method for showing a list of decisions or activities in a transient overlay. Users can open the popup menu that shows up close to the triggering component with just a solitary tap on a symbol or widget.

In this article, we will Explore Focused Pop-Up Menu In Flutter. We see how to execute a demo program. We will tell you how to create a focused pop-up menu utilizing the focused_menu package, and how to work it in your Flutter applications.

  • For Focused Menu:

focused_menu | Flutter package
This is an easy-to-implement package for adding a Focused Long Press Menu to Flutter Applicationspub. dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Constructor

Implementation

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to create a focused pop-up menu in Flutter and how a focused pop-up menu will work using the focused_menu plugin in your Flutter applications. We will show you how to create a pop-up menu and the user presses the item, then a pop-up appears on the screen and blurs the other content on that particular screen. It will be shown on your device.

Demo Module::


Constructor:

To utilize FocusedMenuHolder, you need to call the constructor underneath:

const FocusedMenuHolder(
{Key? key,
required this.child,
required this.onPressed,
required this.menuItems,
this.duration,
this.menuBoxDecoration,
this.menuItemExtent,
this.animateMenuItems,
this.blurSize,
this.blurBackgroundColor,
this.menuWidth,
this.bottomOffsetHeight,
this.menuOffset,
this.openWithTap = false})
: super(key: key);

In this constructor, there was three data were required child, onPressed, and menuItems, when you will use this method.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
focused_menu: ^1.0.5

Step 2: Import

import 'package:focused_menu/focused_menu.dart';
import 'package:focused_menu/modals.dart';

Step 3: Run flutter packages get in the root directory of your app.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

In the main .dart file. We will create a new class MyHomePage(). We will make a list of a string of imageList is equal to the list of network images inside in square bracket

.List<String> imageList = [
'https://cdn.pixabay.com/photo/2019/03/15/09/49/girl-4056684_960_720.jpg',
'https://cdn.pixabay.com/photo/2020/12/15/16/25/clock-5834193__340.jpg',
'https://cdn.pixabay.com/photo/2020/09/18/19/31/laptop-5582775_960_720.jpg',
'https://media.istockphoto.com/photos/woman-kayaking-in-fjord-in-norway-picture-id1059380230?b=1&k=6&m=1059380230&s=170667a&w=0&h=kA_A_XrhZJjw2bo5jIJ7089-VktFK0h0I4OWDqaac0c=',
'https://cdn.pixabay.com/photo/2019/11/05/00/53/cellular-4602489_960_720.jpg',
'https://cdn.pixabay.com/photo/2017/02/12/10/29/christmas-2059698_960_720.jpg',
'https://cdn.pixabay.com/photo/2020/01/29/17/09/snowboard-4803050_960_720.jpg',
'https://cdn.pixabay.com/photo/2020/02/06/20/01/university-library-4825366_960_720.jpg',
'https://cdn.pixabay.com/photo/2020/11/22/17/28/cat-5767334_960_720.jpg',
'https://cdn.pixabay.com/photo/2020/12/13/16/22/snow-5828736_960_720.jpg',
'https://cdn.pixabay.com/photo/2020/12/09/09/27/women-5816861_960_720.jpg',
];

In the body, we will create a gridview. In this GridView.builder() method, we will add itemCount as the length of imageList, gridDelegate as crossAxisCount was 2, mainAxisSpacing was 20, crossAxisSpacing was 20 are wrap to SliverGridDelegateWithFixedCrossAxisCount, itemBuilder as return ClipRRect with borderRadius was 20 and its child we will add imageList[index].

GridView.builder(
itemCount: imageList.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 20,
crossAxisSpacing: 20,
),
itemBuilder: (BuildContext context, int index) {
return ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Image.network(
imageList[index],
fit: BoxFit.fill,
),
);
},
),
When we run the application, we ought to get the screen’s output like the underneath screen capture.

Now we will add FocusedMenuHolder on the GridView.builder().

We will add a return FocusedMenuHolder() method on the itemBuilder function. In this method, we will add menu width size using a media query was 0.5 (50%). We will add that openWithTap was true because of avoiding the long press element. When any user taps on an element then op up will be shown.

GridView.builder(
itemCount: imageList.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 20,
crossAxisSpacing: 20,
),
itemBuilder: (BuildContext context, int index) {
return FocusedMenuHolder(
menuWidth: MediaQuery.of(context).size.width*0.5,
openWithTap: true,
menuItems: [
FocusedMenuItem(
title: const Text("Info"),
trailingIcon: const Icon(Icons.info, color: Colors.orange,),
onPressed: () {}),
FocusedMenuItem(
title: const Text("Bookmark"),
trailingIcon: const Icon(Icons.bookmark_add,color: Colors.teal,),
onPressed: () {}),
FocusedMenuItem(
title: const Text("Favorite"),
trailingIcon: const Icon(Icons.favorite, color: Colors.red,),
onPressed: () {}),
FocusedMenuItem(
title: const Text(
"Share",
),
trailingIcon: const Icon(Icons.share,color: Colors.cyan,),
onPressed: () {}),
],
onPressed: () {},
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Image.network(
imageList[index],
fit: BoxFit.fill,
),
),
);
},
),

Then, we will add menuItems as the list of FocusedMenuItem() with title, triailingIcon, onPressed, and also you will add backgroundColor. Also, you will change the color of the icons and handle the onPressed method in FocusedMenuItem as per your requirements.

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_focus_popup_menu_demo/splash_screen.dart';
import 'package:focused_menu/focused_menu.dart';
import 'package:focused_menu/modals.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Splash(),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

List<String> imageList = [
'https://cdn.pixabay.com/photo/2019/03/15/09/49/girl-4056684_960_720.jpg',
'https://cdn.pixabay.com/photo/2020/12/15/16/25/clock-5834193__340.jpg',
'https://cdn.pixabay.com/photo/2020/09/18/19/31/laptop-5582775_960_720.jpg',
'https://media.istockphoto.com/photos/woman-kayaking-in-fjord-in-norway-picture-id1059380230?b=1&k=6&m=1059380230&s=170667a&w=0&h=kA_A_XrhZJjw2bo5jIJ7089-VktFK0h0I4OWDqaac0c=',
'https://cdn.pixabay.com/photo/2019/11/05/00/53/cellular-4602489_960_720.jpg',
'https://cdn.pixabay.com/photo/2017/02/12/10/29/christmas-2059698_960_720.jpg',
'https://cdn.pixabay.com/photo/2020/01/29/17/09/snowboard-4803050_960_720.jpg',
'https://cdn.pixabay.com/photo/2020/02/06/20/01/university-library-4825366_960_720.jpg',
'https://cdn.pixabay.com/photo/2020/11/22/17/28/cat-5767334_960_720.jpg',
'https://cdn.pixabay.com/photo/2020/12/13/16/22/snow-5828736_960_720.jpg',
'https://cdn.pixabay.com/photo/2020/12/09/09/27/women-5816861_960_720.jpg',
];

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Colors.cyan,
title: Text(widget.title),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(12),
child: GridView.builder(
itemCount: imageList.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 20,
crossAxisSpacing: 20,
),
itemBuilder: (BuildContext context, int index) {
return FocusedMenuHolder(
menuWidth: MediaQuery.of(context).size.width*0.5,
openWithTap: true,
menuItems: [
FocusedMenuItem(
title: const Text("Info"),
trailingIcon: const Icon(Icons.info, color: Colors.orange,),
onPressed: () {}),
FocusedMenuItem(
title: const Text("Bookmark"),
trailingIcon: const Icon(Icons.bookmark_add,color: Colors.teal,),
onPressed: () {}),
FocusedMenuItem(
title: const Text("Favorite"),
trailingIcon: const Icon(Icons.favorite, color: Colors.red,),
onPressed: () {}),
FocusedMenuItem(
title: const Text(
"Share",
),
trailingIcon: const Icon(Icons.share,color: Colors.cyan,),
onPressed: () {}),
],
onPressed: () {},
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Image.network(
imageList[index],
fit: BoxFit.fill,
),
),
);
},
),
),
),
);
}
}


Conclusion:

In the article, I have explained the Focused Pop-Up Menu in Flutter; you can modify this code according to your choice. This was a small introduction to the Focused Pop-Up Menu in Flutter User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying Focused Pop-Up Menu in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on the Focused Pop-Up Menu using the focused_menu plugin in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤


If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Explore Line Chart In Flutter

0

In this article, we will Explore Line Chart In Flutter. We see how to execute a demo program. We will tell you how to create an interactive line chart utilizing the fl_chart package, and how to work it in your Flutter applications.

  • For FL Chart:

fl_chart 0.64.0 | Flutter package
A highly customizable Flutter chart library that supports Line Chart, Bar Chart, Pie Chart, Scatter Chart, and Radar…pub.dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Constructor

Properties

Implementation

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to create an interactive line chart in Flutter and how a line chart will work using the fl_chart plugin in your Flutter applications. We will show you how to create a line chart, and the user presses the line and then shows data on this particular line. It will be shown on your device.

Demo Module::


Constructor:

  • To utilize LineChart, you need to call the constructor underneath:
const LineChart(
this.data, {
this.chartRendererKey,
super.key,
super.duration = const Duration(milliseconds: 150),
super.curve = Curves.linear,
});
  • In LineChart we will use the LineChartData constructor on the data field:
LineChartData({
this.lineBarsData = const [],
this.betweenBarsData = const [],
super.titlesData = const FlTitlesData(),
super.extraLinesData = const ExtraLinesData(),
this.lineTouchData = const LineTouchData(),
this.showingTooltipIndicators = const [],
super.gridData = const FlGridData(),
super.borderData,
super.rangeAnnotations = const RangeAnnotations(),
double? minX,
double? maxX,
super.baselineX,
double? minY,
double? maxY,
super.baselineY,
super.clipData = const FlClipData.none(),
super.backgroundColor,
})

Properties:

There are some properties of LineChartData:

  • > lineBarsData: This property is utilized to draw some lines in various shapes and overlap them.
  • > betweenBarsData: This property is utilized to fill the area between two LineChartBarData with a color or gradient.
  • > lineTouchData: This property is utilized to handle touch behaviors and responses.
  • > showingTooltipIndicators: This property is utilized to show some a popup with information on top of each [LineChartBarData.spots]. Just put line indicator numbers and spot indices you want to show on top of them.
  • > titlesData: This property is utilized to hold data for showing titles on each side of the charts.
  • > gridData: This property is utilized to be responsible for rendering grid lines behind the content of charts, [show] determines showing or hiding all grids.
  • > borderData: This property is utilized to [show] determine to show or hide borders around the chart. [border] Determines the visual look of 4 borders.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
fl_chart: ^0.64.0

Step 2: Import

import 'package:fl_chart/fl_chart.dart';

Step 3: Run flutter packages get in the root directory of your app.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

In the main .dart file. We will create a new class MyHomePage(). In this class, we will define a list of <int> showingTooltipOnSpots is equal to 21 in the bracket. It shows when the app runs default shows a popup and line on the 21 number. List<int> showingTooltipOnSpots = [21];

Now, we will create a list of FlSpot. It determines the axis based on horizontal and vertical positions.

List<FlSpot> get allSpots => const [
FlSpot(0, 20),
FlSpot(1, 30),
FlSpot(2, 40),
FlSpot(3, 50),
FlSpot(4, 35),
FlSpot(5, 40),
FlSpot(6, 30),
FlSpot(7, 20),
FlSpot(8, 25),
FlSpot(9, 40),
FlSpot(10, 50),
FlSpot(11, 35),
FlSpot(12, 50),
FlSpot(13, 60),
FlSpot(14, 40),
FlSpot(15, 50),
FlSpot(16, 20),
FlSpot(17, 25),
FlSpot(18, 40),
FlSpot(19, 50),
FlSpot(20, 35),
FlSpot(21, 80),
FlSpot(22, 30),
FlSpot(23, 20),
FlSpot(24, 25),
FlSpot(25, 40),
];

Now, we will create lineBarsData is equal to the LineChartBarData() method. In this method, we will add showingIndicators is equal to showingTooltipOnSpots, spots are equal to the allSpots, also add barWidth, gradient, dotData, etc.

final tooltipsOnBar = lineBarsData[0];

final lineBarsData = [
LineChartBarData(
showingIndicators: showingTooltipOnSpots,
spots: allSpots,
isCurved: false,
barWidth: 3,
belowBarData: BarAreaData(
show: true,
gradient: LinearGradient(colors: [
const Color(0xff9DCEFF).withOpacity(0.4),
const Color(0xff92A3FD).withOpacity(0.1),
], begin: Alignment.topCenter, end: Alignment.bottomCenter),
),
dotData: const FlDotData(show: false),
gradient: const LinearGradient(
colors: [Color(0xff9DCEFF), Color(0xff92A3FD)],
),
),
];

In the body, we will add the LineChart() method. Inside this method, we will add the LineChartData() method. In this method, we will add showingTooltipIndicators show showingTooltipOnSpots.map((index) return ShowingTooltipIndicators with LineBarSpot. It shows some pop-up information on top of the line. We will add lineTouchData where enable was true and it is used to handle the touch behavior.

LineChart(
LineChartData(
showingTooltipIndicators:
showingTooltipOnSpots.map((index) {
return ShowingTooltipIndicators([
LineBarSpot(
tooltipsOnBar,
lineBarsData.indexOf(tooltipsOnBar),
tooltipsOnBar.spots[index],
),
]);
}).toList(),
lineTouchData: LineTouchData(
enabled: true,
handleBuiltInTouches: false,
touchCallback: (FlTouchEvent event,
LineTouchResponse? response) {
if (response == null ||
response.lineBarSpots == null) {
return;
}
if (event is FlTapUpEvent) {
final spotIndex =
response.lineBarSpots!.first.spotIndex;
showingTooltipOnSpots.clear();
setState(() {
showingTooltipOnSpots.add(spotIndex);
});
}
},
mouseCursorResolver: (FlTouchEvent event,
LineTouchResponse? response) {
if (response == null ||
response.lineBarSpots == null) {
return SystemMouseCursors.basic;
}
return SystemMouseCursors.click;
},
getTouchedSpotIndicator: (LineChartBarData barData,
List<int> spotIndexes) {
return spotIndexes.map((index) {
return TouchedSpotIndicatorData(
const FlLine(
color: Colors.red,
),
FlDotData(
show: true,
getDotPainter:
(spot, percent, barData, index) =>
FlDotCirclePainter(
radius: 3,
color: Colors.white,
strokeWidth: 3,
strokeColor: const Color(0xffC58BF2),
),
),
);
}).toList();
},
touchTooltipData: LineTouchTooltipData(
tooltipBgColor: const Color(0xffC58BF2),
tooltipRoundedRadius: 20,
getTooltipItems: (List<LineBarSpot> lineBarsSpot) {
return lineBarsSpot.map((lineBarSpot) {
return LineTooltipItem(
"${lineBarSpot.x.toInt()} mins ago",
const TextStyle(
color: Colors.white,
fontSize: 10,
fontWeight: FontWeight.bold,
),
);
}).toList();
},
),
),
lineBarsData: lineBarsData,
minY: 0,
maxY: 110,
titlesData: const FlTitlesData(
show: false,
),
gridData: const FlGridData(show: false),
borderData: FlBorderData(
show: true,
border: Border.all(
color: Colors.transparent,
),
),
),
),

Then, we will add lineBarsData is equal to the variable lineBarsData that we will already create, minY is zero, maxY is 110, titlesData, gridData, and borderData.

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Code File:

import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter_line_chart_data_demo/splash_screen.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const Splash(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<int> showingTooltipOnSpots = [21];

  List<FlSpot> get allSpots => const [
        FlSpot(0, 20),
        FlSpot(1, 30),
        FlSpot(2, 40),
        FlSpot(3, 50),
        FlSpot(4, 35),
        FlSpot(5, 40),
        FlSpot(6, 30),
        FlSpot(7, 20),
        FlSpot(8, 25),
        FlSpot(9, 40),
        FlSpot(10, 50),
        FlSpot(11, 35),
        FlSpot(12, 50),
        FlSpot(13, 60),
        FlSpot(14, 40),
        FlSpot(15, 50),
        FlSpot(16, 20),
        FlSpot(17, 25),
        FlSpot(18, 40),
        FlSpot(19, 50),
        FlSpot(20, 35),
        FlSpot(21, 80),
        FlSpot(22, 30),
        FlSpot(23, 20),
        FlSpot(24, 25),
        FlSpot(25, 40),
      ];

  @override
  Widget build(BuildContext context) {
    final lineBarsData = [
      LineChartBarData(
        showingIndicators: showingTooltipOnSpots,
        spots: allSpots,
        isCurved: false,
        barWidth: 3,
        belowBarData: BarAreaData(
          show: true,
          gradient: LinearGradient(colors: [
            const Color(0xff9DCEFF).withOpacity(0.4),
            const Color(0xff92A3FD).withOpacity(0.1),
          ], begin: Alignment.topCenter, end: Alignment.bottomCenter),
        ),
        dotData: const FlDotData(show: false),
        gradient: const LinearGradient(
          colors: [Color(0xff9DCEFF), Color(0xff92A3FD)],
        ),
      ),
    ];

    final tooltipsOnBar = lineBarsData[0];
    var media = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
        centerTitle: true,
        automaticallyImplyLeading: false,
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.circular(25),
              child: Container(
                height: media.width * 0.8,
                width: double.maxFinite,
                decoration: BoxDecoration(
                  color: const Color(0xff9DCEFF).withOpacity(0.3),
                  borderRadius: BorderRadius.circular(25),
                ),
                child: Stack(
                  alignment: Alignment.topLeft,
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(
                          vertical: 20, horizontal: 20),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            "Heart Rate",
                            style: TextStyle(
                                color: Colors.black,
                                fontSize: 16,
                                fontWeight: FontWeight.w700),
                          ),
                          ShaderMask(
                            blendMode: BlendMode.srcIn,
                            shaderCallback: (bounds) {
                              return const LinearGradient(
                                      colors: [
                                    Color(0xff9DCEFF),
                                    Color(0xff92A3FD)
                                  ],
                                      begin: Alignment.centerLeft,
                                      end: Alignment.centerRight)
                                  .createShader(Rect.fromLTRB(
                                      0, 0, bounds.width, bounds.height));
                            },
                            child: Text(
                              "78 BPM",
                              style: TextStyle(
                                  color: Colors.white.withOpacity(0.7),
                                  fontWeight: FontWeight.w700,
                                  fontSize: 18),
                            ),
                          ),
                        ],
                      ),
                    ),
                    LineChart(
                      LineChartData(
                        showingTooltipIndicators:
                            showingTooltipOnSpots.map((index) {
                          return ShowingTooltipIndicators([
                            LineBarSpot(
                              tooltipsOnBar,
                              lineBarsData.indexOf(tooltipsOnBar),
                              tooltipsOnBar.spots[index],
                            ),
                          ]);
                        }).toList(),
                        lineTouchData: LineTouchData(
                          enabled: true,
                          handleBuiltInTouches: false,
                          touchCallback: (FlTouchEvent event,
                              LineTouchResponse? response) {
                            if (response == null ||
                                response.lineBarSpots == null) {
                              return;
                            }
                            if (event is FlTapUpEvent) {
                              final spotIndex =
                                  response.lineBarSpots!.first.spotIndex;
                              showingTooltipOnSpots.clear();
                              setState(() {
                                showingTooltipOnSpots.add(spotIndex);
                              });
                            }
                          },
                          mouseCursorResolver: (FlTouchEvent event,
                              LineTouchResponse? response) {
                            if (response == null ||
                                response.lineBarSpots == null) {
                              return SystemMouseCursors.basic;
                            }
                            return SystemMouseCursors.click;
                          },
                          getTouchedSpotIndicator: (LineChartBarData barData,
                              List<int> spotIndexes) {
                            return spotIndexes.map((index) {
                              return TouchedSpotIndicatorData(
                                const FlLine(
                                  color: Colors.red,
                                ),
                                FlDotData(
                                  show: true,
                                  getDotPainter:
                                      (spot, percent, barData, index) =>
                                          FlDotCirclePainter(
                                    radius: 3,
                                    color: Colors.white,
                                    strokeWidth: 3,
                                    strokeColor: const Color(0xffC58BF2),
                                  ),
                                ),
                              );
                            }).toList();
                          },
                          touchTooltipData: LineTouchTooltipData(
                            tooltipBgColor: const Color(0xffC58BF2),
                            tooltipRoundedRadius: 20,
                            getTooltipItems: (List<LineBarSpot> lineBarsSpot) {
                              return lineBarsSpot.map((lineBarSpot) {
                                return LineTooltipItem(
                                  "${lineBarSpot.x.toInt()} mins ago",
                                  const TextStyle(
                                    color: Colors.white,
                                    fontSize: 10,
                                    fontWeight: FontWeight.bold,
                                  ),
                                );
                              }).toList();
                            },
                          ),
                        ),
                        lineBarsData: lineBarsData,
                        minY: 0,
                        maxY: 110,
                        titlesData: const FlTitlesData(
                          show: false,
                        ),
                        gridData: const FlGridData(show: false),
                        borderData: FlBorderData(
                          show: true,
                          border: Border.all(
                            color: Colors.transparent,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}



Conclusion:

In the article, I have explained the Line Chart in Flutter; you can modify this code according to your choice. This was a small introduction to the Line Chart in Flutter User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying Line Chart in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on the Line Chart using the fl_chart plugin in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤


If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Virtual 3D Tour In Flutter

0

In this article, we will explore the Virtual 3D Tour In Flutter. We see how to execute a demo program. We will tell you how to create an interactive virtual 3D tour and 360 view utilizing the panorama package, and how to work it in your Flutter applications.

  • For Panorama:

panorama package – All Versions
Pub is the package manager for the Dart programming language, containing reusable libraries & packages for Flutter and…pub.dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

We will explore virtual 3d tours and 360 views navigating through rooms, houses, kitchens, and spaces for a lifelike viewing experience. The below demo video shows how to create an interactive virtual 3d tour in Flutter and how a virtual 3d tour will work using the panorama package in your Flutter applications. 

We will show you user presses the button then opens a virtual screen then the user views 3D and 360 views. The user will touch the screen and swipe the image for view 360. It will be shown on your device.

Demo Module::


Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
panorama: ^0.4.1

Step 2: Import

import 'package:panorama/panorama.dart';

Step 3: Add the assets

Add assets to pubspec — yaml file.

assets:
- assets/images/

Step 4: Run flutter packages get in the root directory of your app.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called virtual_modeldart inside the lib folder.

In this virtual model, we will create two final String img and title. We will create a List of the virtual models are:

class VirtualModel {
final String img;
final String title;

VirtualModel(
{required this.img, required this.title,});

static List<VirtualModel> virtualModel = [
VirtualModel(
img: 'assets/images/house.jpg',
title: "Outside House",
),
VirtualModel(
img: 'assets/images/bedroom.jpg',
title: "Bedroom",
),
VirtualModel(
img: 'assets/images/kitchen.jpg',
title: "Kitchen",
),
VirtualModel(
img: 'assets/images/living_room.jpg',
title: "Living Room",
),

];

}

Create a new dart file called main.dart inside the lib folder.

In the main. dart file. We will create a MyHomePage class. In this class, we will add a Column widget on the body part. Inside the column, we will add an image then we will add a Stack widget. Inside the stack, we will add an image with fit, height, and width and wrap it to the FittedBox widget. Also, the FittedBox widget was wrapped to the ClipRRect widget.

Column(
children: [
SizedBox(
height: MediaQuery.of(context).size.height * 0.06,
),
Image.asset(
'assets/images/logo.png',
height: MediaQuery.of(context).size.height * 0.13,
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.1,
),
Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left:6.0, right: 6.0),
child: SizedBox(
width: MediaQuery.of(context).size.width,
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
child: FittedBox(
child: Image.asset(
"assets/images/house.jpg",
fit: BoxFit.cover,
height: MediaQuery.of(context).size.height * 0.4,
width: MediaQuery.of(context).size.width,
),
),
),
),
),
Positioned(
left: 0,
right: 0,
top: MediaQuery.of(context).size.height * 0.31,
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const VirtualScreen()),
);
},
child: Center(
child: Container(
margin: EdgeInsets.symmetric(horizontal: MediaQuery.of(context).size.width * 0.28,),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(15)),
height: MediaQuery.of(context).size.height * 0.04,
child: Row(
children: [
Container(
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
),
height: MediaQuery.of(context).size.height * 0.03,
width: MediaQuery.of(context).size.width * 0.1,
child: const Center(
child: Icon(
Icons.photo,
color: Colors.black,
size: 18,
)),
),
const Text(
"Virtual 3D Tour",
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w700),
)
],
),
),
),
),
),
],
),
],
),

Also, we will add one more item on the Stack widget a container widget. In this widget, we will add an icon and text “Virtual 3D Tour” wrapped to it row widget on its child and the whole conatianer wrapped to the inkwell and navigate to the VirtualScreen(). Below we will deeply discuss the code.

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Create a new class file called Virtual Screen inside the lib folder.

In the virtual screen, we will create a list of variables of the virtual model _virtual is equal to the VirtualModel.virtualModel and also, we will create a String of selectedImage.

final List<VirtualModel> _virtual = VirtualModel.virtualModel;
String? selectedImage;

In the body, we will add the Panorama method. In this method, we will add selectedImage not equal to null then show selectedImage else show a dummy image. Users will select the image to view 3D and 360 views.

Stack(
children: [
Panorama(
child: selectedImage != null
? Image.asset(selectedImage!)
: Image.asset("assets/images/house.jpg"),
),
],
),

Also, this below part was coming into the same stack widget. In this widget, we will add a row widget. In a row widget, we will add a MainAxisAlignment was spaceBetween then add an icon, text “Virtual 3D Tour”, and another icon was wrapped to its Positioned widget.

Positioned(
top: 20,
left: 0,
right: 0,
child: Padding(
padding: const EdgeInsets.only(left: 20, right: 20, top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
decoration: BoxDecoration(
color: Colors.grey.withOpacity(0.7),
borderRadius: BorderRadius.circular(10)),
height: size.height * 0.05,
width: size.width * 0.12,
child: Center(
child: IconButton(
onPressed: () => Navigator.pop(context),
icon: const Icon(
Icons.arrow_back_ios_new_outlined,
color: Colors.black,
))),
),
const Text(
"Virtual 3D Tour",
style: TextStyle(color: Colors.white,fontSize: 18,fontWeight: FontWeight.w700),
),
Container(
decoration: BoxDecoration(
color: Colors.grey.withOpacity(0.7),
borderRadius: BorderRadius.circular(10)),
height: size.height * 0.05,
width: size.width * 0.12,
child: Center(
child: IconButton(
onPressed: () {},
icon: const Icon(
Icons.more_vert,
color: Colors.black,
))),
),
],
),
),
),
Positioned(
bottom: 10,
left: 0,
right: 0,
child: _data()),

We will create another Positioned widget. In this widget, we will add its child was _data() method. Below we will deeply discuss this method.

Now we will discuss the _data() method.

In this method, we will add a return SizedBox widget. In this widget, we will add the ListView.separated method. In this method, we will add the itemCount was _virtual. length, itemBuilder we will return GestureDetector() widget. In this widget, we will add the onTap function. In this function, we will add that selectedImage is equal to the image and wrapped to it setState(). Its child we will add a _virtual[index].image was wrapped to the container.

Widget _data() {
return SizedBox(
height: MediaQuery.of(context).size.height* 0.15,
width: double.infinity,
child: ListView.separated(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: _virtual.length,
itemBuilder: (context, index) {
String image = _virtual[index].img;
return GestureDetector(
onTap: () {
setState(() {
selectedImage = image;
});
},
child: Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Column(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: Colors.white, width: 3)),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.asset(
_virtual[index].img,
fit: BoxFit.fill,
height: MediaQuery.of(context).size.height * 0.1,
width: MediaQuery.of(context).size.width * 0.25,
),
),
),
const SizedBox(
height: 10,
),
Text(
_virtual[index].title,
style: const TextStyle(fontSize: 17,fontWeight: FontWeight.w600),
),
],
),
),
);
},
separatorBuilder: (_, __) => const SizedBox(
width: 10,
),
));
}
When we run the application, we ought to get the screen’s output like the underneath screen capture.

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_virtual_3d_tour_demo/splash_screen.dart';
import 'package:flutter_virtual_3d_tour_demo/virtual_model.dart';
import 'package:panorama/panorama.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.orange),
useMaterial3: true,
),
home: const Splash(),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
children: [
SizedBox(
height: MediaQuery.of(context).size.height * 0.06,
),
Image.asset(
'assets/images/logo.png',
height: MediaQuery.of(context).size.height * 0.13,
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.1,
),
Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left:6.0, right: 6.0),
child: SizedBox(
width: MediaQuery.of(context).size.width,
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
child: FittedBox(
child: Image.asset(
"assets/images/house.jpg",
fit: BoxFit.cover,
height: MediaQuery.of(context).size.height * 0.4,
width: MediaQuery.of(context).size.width,
),
),
),
),
),
Positioned(
left: 0,
right: 0,
top: MediaQuery.of(context).size.height * 0.31,
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const VirtualScreen()),
);
},
child: Center(
child: Container(
margin: EdgeInsets.symmetric(horizontal: MediaQuery.of(context).size.width * 0.28,),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(15)),
height: MediaQuery.of(context).size.height * 0.04,
child: Row(
children: [
Container(
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
),
height: MediaQuery.of(context).size.height * 0.03,
width: MediaQuery.of(context).size.width * 0.1,
child: const Center(
child: Icon(
Icons.photo,
color: Colors.black,
size: 18,
)),
),
const Text(
"Virtual 3D Tour",
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w700),
)
],
),
),
),
),
),

],
),
],
),
),
);
}
}

class VirtualScreen extends StatefulWidget {

const VirtualScreen({super.key,});

@override
State<VirtualScreen> createState() => _VirtualScreenState();
}

class _VirtualScreenState extends State<VirtualScreen> {
final List<VirtualModel> _virtual = VirtualModel.virtualModel;
String? selectedImage;

@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Scaffold(
body: Stack(
children: [
Panorama(
child: selectedImage != null
? Image.asset(selectedImage!)
: Image.asset("assets/images/house.jpg"),
),
Positioned(
top: 20,
left: 0,
right: 0,
child: Padding(
padding: const EdgeInsets.only(left: 20, right: 20, top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
decoration: BoxDecoration(
color: Colors.grey.withOpacity(0.7),
borderRadius: BorderRadius.circular(10)),
height: size.height * 0.05,
width: size.width * 0.12,
child: Center(
child: IconButton(
onPressed: () => Navigator.pop(context),
icon: const Icon(
Icons.arrow_back_ios_new_outlined,
color: Colors.black,
))),
),
const Text(
"Virtual 3D Tour",
style: TextStyle(color: Colors.white,fontSize: 18,fontWeight: FontWeight.w700),
),
Container(
decoration: BoxDecoration(
color: Colors.grey.withOpacity(0.7),
borderRadius: BorderRadius.circular(10)),
height: size.height * 0.05,
width: size.width * 0.12,
child: Center(
child: IconButton(
onPressed: () {},
icon: const Icon(
Icons.more_vert,
color: Colors.black,
))),
),
],
),
),
),
Positioned(
bottom: 10,
left: 0,
right: 0,
child: _data()),
],
),
);
}

Widget _data() {
return SizedBox(
height: MediaQuery.of(context).size.height* 0.15,
width: double.infinity,
child: ListView.separated(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: _virtual.length,
itemBuilder: (context, index) {
String image = _virtual[index].img;
return GestureDetector(
onTap: () {
setState(() {
selectedImage = image;
});
},
child: Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Column(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: Colors.white, width: 3)),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.asset(
_virtual[index].img,
fit: BoxFit.fill,
height: MediaQuery.of(context).size.height * 0.1,
width: MediaQuery.of(context).size.width * 0.25,
),
),
),
const SizedBox(
height: 10,
),
Text(
_virtual[index].title,
style: const TextStyle(fontSize: 17,fontWeight: FontWeight.w600),
),
],
),
),
);
},
separatorBuilder: (_, __) => const SizedBox(
width: 10,
),
));
}
}

Conclusion:

In the article, I have explained the Virtual 3D Tour in Flutter; you can modify this code according to your choice. This was a small introduction to the Virtual 3D Tour in Flutter User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying Virtual 3D Tour in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on the Virtual 3D Tour using the panorama package in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


2026 Comprehensive Guide to Automation Testing in Flutter with…

0

In this article, we will explore Automation Testing using Appium In Flutter. We perceive how to execute a demo program. We will show you how to automation testing using appium will work in your Flutter applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Contents :

Introduction

Why Automation Testing in Flutter?

Installing Appium for Flutter

Conclusion

GitHub Link

Reference Url


Introduction:

In the fast-evolving landscape of mobile app development, ensuring the robustness and reliability of your Flutter applications is paramount. Automation testing emerges as a crucial ally in this pursuit, providing developers with the means to streamline the testing process and enhance the overall quality of their applications.

Welcome to our comprehensive guide on “Automation Testing Using Appium in Flutter,” where we delve into the powerful synergy between Flutter and Appium to elevate your testing strategy.

Why Automation Testing in Flutter?:

As Flutter continues to gain popularity for its cross-platform capabilities and expressive UI, the demand for efficient testing methodologies has never been higher. Automation testing proves to be a game-changer, allowing developers to catch bugs early, reduce manual testing efforts, and ensure a seamless user experience across diverse devices.

Enter Appium: A Cross-Platform Testing Solution:

Appium is a versatile and open-source automation tool that seamlessly integrates with Flutter applications. Whether you’re targeting Android or iOS, Appium provides a unified framework for testing, simplifying the complexities associated with multi-platform development.

What to Expect in This Guide:

In the upcoming sections, we will explore the fundamentals of automation testing in the Flutter framework, understand the key benefits of leveraging Appium, and walk through practical examples to get you started. Whether you’re a seasoned Flutter developer or just starting your journey, this guide aims to demystify the process of automation testing in Flutter using the powerful capabilities of Appium.

Let’s embark on this journey to enhance the reliability and efficiency of your Flutter applications through automation testing. Ready to dive in?

Installing Appium for Flutter:

Installing Appium for Flutter involves setting up Appium and its dependencies to enable automated testing of Flutter applications. Here are the general steps for installing Appium in the context of Flutter:

1. Install Node.js:

  • Appium is built on Node.js, so you need to have Node.js installed on your machine.

2. Install Appium Server:

  • You can install Appium globally using npm (Node Package Manager) by running the following command in your terminal or command prompt:
npm install -g appium

3. Install Appium Dependencies:

  • Depending on your testing requirements, you might need additional dependencies. For example, if you plan to automate on Android, you’ll need the Android SDK installed and configured.
  • For iOS testing, you’ll need Xcode installed on a Mac machine.

4. Install Flutter Driver:

  • Flutter Driver is a package that allows communication between the Flutter app and the Appium server for testing. You can add Flutter Driver to your Flutter project by adding it to your pubspec.yaml file and running flutter pub get. For example:
dev_dependencies:
flutter_driver:
sdk: flutter

5. Start Appium Server:

  • After installation, start the Appium server by running the following command in your terminal or command prompt:
appium

6. Configure and Run Your Flutter App:

  • Ensure your Flutter app is set up for testing. You should add some additional configurations to your app code to make it testable with Flutter Driver.

7. Run Appium Tests:

  • Write your automated tests using Flutter Driver and execute them. You can run your tests from the command line or use a testing framework like flutter test.
Let’s dive into the code part. For running the test cases we’re going to use the Visual Studio Code as our code editor.

To set up Appium for Flutter automation testing using Visual Studio Code (VS Code), you need to follow these steps:

1. Install Required Software:

  • Visual Studio Code: Download and install VS Code from the official website.
  • Node.js and npm: Install Node.js from the official website, which includes npm (Node Package Manager).

2. Install Appium:

  • Install Appium globally using npm by running the following command in your terminal or command prompt:
npm install -g appium

3. Install Appium Flutter Driver:

  • Appium Flutter Driver is a test automation tool for Flutter applications. Install it by running the following command in your terminal:
npm install -g appium-flutter-driver

4. Install Flutter SDK:

  • Install the Flutter SDK by following the instructions provided on the Flutter website.

5. Configure Flutter Environment Variables:

  • Add Flutter’s bin directory to your system’s PATH variable. This allows you to run Flutter commands from any terminal window.
  • You can do this by adding the following line to your system’s .bash_profile.bashrc.zshrc, or similar file:
export PATH="$PATH:/path/to/flutter/bin"
  • Replace /path/to/flutter/bin with the actual path where you installed the Flutter SDK.

6. Install Flutter Plugin for VS Code:

  • Launch VS Code.
  • Go to the Extensions view by clicking on the square icon in the sidebar or pressing Ctrl+Shift+X.
  • Search for “Flutter” in the extensions search bar.
  • Install the Flutter extension provided by the Flutter team.

7. Create a Flutter Project:

  • Create a new Flutter project or open an existing one in VS Code.
  • Ensure your Flutter project is properly set up and can run on a device, emulator/simulator.

8. Configure Appium Server:

  • Start the Appium server by running the following command in your terminal:
appium
  • Make sure Appium is running and listening for connections on the default host and port (http://localhost:4723).

9. Write Flutter Automation Tests:

  • Write your Flutter automation tests using the Appium Flutter Driver API.
  • You can use any testing framework such as Flutter’s built-in flutter_test framework, or third-party libraries like flutter_gherkin for behavior-driven development (BDD).
  • Install all the essential libraries for writing test cases, such as assert, flutter-finder, flutter-driver etc.

I created a separate folder for writing my test cases(flutter-classes).
Here, paste the build folder you’ll get after running the app in debug mode.

Now run the test case by using the command
npx wdio run wdio.android.conf.js

You can edit the path of your build folder from the file “wdio.android.conf.js”.

Find the complete code in the below GitHub link.

Conclusion:-

With the insights gained from this blog, you now possess the expertise and resources to implement Appium for automation testing in Flutter apps, opening doors to diverse testing opportunities. Embrace this journey of discovery and advancement in your projects!

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


GitHub – flutter-devs/appium_flutter
Contribute to flutter-devs/appium_flutter development by creating an account on GitHub.github.com

Reference Url:-

How to Test Flutter Apps Using Appium Automation | BrowserStack
Step-by-step tutorial on how to automate Flutter app testing with Appium using examples. Learn how to run UI tests…www.browserstack.com


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


2026 Ultimate Guide: Moving Marker Along Polyline on Google Ma…


In this article, we will explore the Moving Marker Using Polyline On Google Maps In Flutter. We see how to execute a demo program. We will tell you the best way how to move markers from one location to another location using polyline on Google Maps in your Flutter applications.

  • For Google Maps Flutter:

google_maps_flutter | Flutter package
A Flutter plugin for integrating Google Maps in iOS and Android applications.pub.dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to create a moving marker On Google Maps in Flutter and how a moving marker will work on Google Maps using polyline in your Flutter applications. We will create a marker they will move from one location to another location on Google Maps using polyline. It will be shown on your device.

Demo Module::


Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.
dependencies:
flutter:
sdk: flutter
google_maps_flutter: ^2.5.2

Step 2: Import

import 'package:google_maps_flutter/google_maps_flutter.dart';

Step 3: Run flutter packages get in the root directory of your app.

Step 4: Update the build.gradle File

Set the minSdkVersion in android/app/build.gradle:
android {
defaultConfig {
minSdkVersion 20
}
}

Step 5: Add API Key

  • For Andriod:
Add the Api key in android/app/src/main/AndroidManifest.xml:
<manifest ...
<application ...
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY_HERE"/>
</application>
</manifest>
  • For Ios:
To set up, specify your API key in the application delegate ios/Runner/AppDelegate.m:
import GoogleMaps
...
GMSServices.provideAPIKey("YOUR_API_KEY_HERE")

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

In the main .dart file. We will create a new class MyHomePage(). In this class, we will define a GoogleMapControlle:r as a mapController variable and Set Polylines as a polylines variable ie equal to a curly bracket.GoogleMapController? mapController;
Set<Polyline> polylines = {};

Now, we will set the marker variable was markers are equal to the Set(). Also, we will add an initial current location was available loc1 is equal to the LatLng(). Set<Marker> markers = Set();
LatLng loc1 = const LatLng(28.612898, 77.365930);

Then, we will add the two position variables pos1 and pos2 of the polylines.

  • late LatLng pos1;
  • late LatLng pos2;

Now, we will add the initState() method. In this method, we will add the initial position of the moving marker was the position is equal to loc1.latitude, loc1.longitude in square bracket. Also, the pos1 and pos2 variable is equal to the loc1. in this method, we will add the addMarkers() method. We will define the below code.

@override
void initState() {
position = [
loc1.latitude,
loc1.longitude
]; //initial position of moving marker
pos1 = loc1;
pos2 = loc1;
addMarkers();
super.initState();
}

We will create the addMarkers() method. In this method, we will add marderId, position, and icon.

addMarkers() async {
markers.add(Marker(
markerId: MarkerId(loc1.toString()),
position: loc1,
icon: BitmapDescriptor.defaultMarker));
setState(() {
});
}

We will create an animation() method. In this method, start the moving marker. Another, method we will create is movingMarker(). We will dine the below code.

animation(result) {
i = 0;
deltaLat = (result[0] - position[0]) / numDeltas;
deltaLng = (result[1] - position[1]) / numDeltas;
movingMarker();
}
movingMarker() {
position[0] += deltaLat;
position[1] += deltaLng;
var latlng = LatLng(position[0], position[1]);

markers = {
Marker(
markerId: const MarkerId("moving marker"),
position: latlng,
icon: BitmapDescriptor.defaultMarker,
)
};

pos1 = pos2;
pos2 = LatLng(position[0], position[1]);

polylines.add(Polyline(
polylineId: PolylineId(pos2.toString()),
visible: true,
width: 5,
//width of polyline
points: [
pos1,
pos2,
],
color: Colors.blue, //color of polyline
));

setState(() {
});

if (i != numDeltas) {
i++;
Future.delayed(Duration(milliseconds: delay), () {
movingMarker();
});
}
}

In the body part, we will add the GoogleMap() method. In this method, we will add zoomGesturesEnabled was true, set the initialCameraPosition as zoom is 14, and the target was your loc1 wrap to CameraPosition(), add variable on polylines, map type was normal.

GoogleMap(
zoomGesturesEnabled: true,
initialCameraPosition: CameraPosition(
target: loc1,
zoom: 14.0,
),
markers: markers,
polylines: polylines,
mapType: MapType.normal,
onMapCreated: (controller) {
//method called when map is created
setState(() {
mapController = controller;
});
},
)

onMapCreated was this method called when a map is created. Inside onMapCreated, we will add the setState() function. In this function, we will add mapController is equal to the controller. We will add the variable markers on markers.

Now, we will create a FloatingActionButton(). In this button, we will add backgroundColor was red.shade300, its child adds the text “Start Moving”.

floatingActionButton: SizedBox(
height: MediaQuery.of(context).size.height * 0.3,
width: MediaQuery.of(context).size.width * 0.175,
child: FloatingActionButton(
backgroundColor: Colors.red.shade300,
child: const Center(
child: Text(
"Start\nMoving",
textAlign: TextAlign.center,
)),
onPressed: () {
var result = [28.6279, 77.3749];
animation(result);
},
),
),

onPressed we will add the latitude and longitude of the new position if was var result is equal to the [28.6279, 77.3749] also add animation(result) for the start moving marker.

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_polylines_moving_marker_demo/splash_screen.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Splash(),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
GoogleMapController? mapController;
Set<Polyline> polylines = {};

Set<Marker> markers = Set();

LatLng loc1 = const LatLng(28.612898, 77.365930);

int numDeltas = 40;
int delay = 40;
var i = 0;
double? deltaLat;
double? deltaLng;
var position;

late LatLng pos1;
late LatLng pos2;

@override
void initState() {
position = [loc1.latitude, loc1.longitude];
pos1 = loc1;
pos2 = loc1;
addMarkers();
super.initState();
}

addMarkers() async {
markers.add(Marker(
markerId: MarkerId(loc1.toString()),
position: loc1,
icon: BitmapDescriptor.defaultMarker));

setState(() {});
}

animation(result) {
i = 0;
deltaLat = (result[0] - position[0]) / numDeltas;
deltaLng = (result[1] - position[1]) / numDeltas;
movingMarker();
}

movingMarker() {
position[0] += deltaLat;
position[1] += deltaLng;
var latlng = LatLng(position[0], position[1]);

markers = {
Marker(
markerId: const MarkerId("moving marker"),
position: latlng,
icon: BitmapDescriptor.defaultMarker,
)
};

pos1 = pos2;
pos2 = LatLng(position[0], position[1]);

polylines.add(Polyline(
polylineId: PolylineId(pos2.toString()),
visible: true,
width: 5,
//width of polyline
points: [
pos1,
pos2,
],
color: Colors.blue, //color of polyline
));

setState(() {
//refresh UI
});

if (i != numDeltas) {
i++;
Future.delayed(Duration(milliseconds: delay), () {
movingMarker();
});
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text(
"Flutter Moving Marker Using Polylines",
),
backgroundColor: Colors.red.shade300,
),
floatingActionButton: SizedBox(
height: MediaQuery.of(context).size.height * 0.3,
width: MediaQuery.of(context).size.width * 0.175,
child: FloatingActionButton(
backgroundColor: Colors.red.shade300,
child: const Center(
child: Text(
"Start\nMoving",
textAlign: TextAlign.center,
)),
onPressed: () {
var result = [28.6279, 77.3749];

animation(result);
},
),
),
body: GoogleMap(
zoomGesturesEnabled: true,
initialCameraPosition: CameraPosition(
target: loc1,
zoom: 14.0,
),
markers: markers,
polylines: polylines,
mapType: MapType.normal,
onMapCreated: (controller) {
setState(() {
mapController = controller;
});
},
));
}
}

Conclusion:

In the article, I have explained the Moving Marker Using Polyline On Google Maps In Flutter; you can modify this code according to your choice. This was a small introduction to the Moving Marker Using Polyline On Google Maps In Flutter User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying Moving Marker Using Polyline On Google Maps in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on moving marker using polyline on Google Maps to show marker was moving from one location to another location using polyline and also draw a line in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Vibration In Flutter

In this article, we will explore the Vibration In Flutter. We perceive how to execute a demo program. We will let you know how to implement OnTap vibration using two methods first, without the package is the HapticFeedback class, and second, with the package is the vibration package. We will look out for both methods for giving a vibration effect when the user taps on the screen or performs any event in your Flutter applications.

  • For HapticFeedback class:

HapticFeedback class – services library – Dart API
API docs for the HapticFeedback class from the services library, for the Dart programming language.api.flutter.dev

  • For Vibration:

vibration | Flutter package
A plugin for handling Vibration API on iOS, Android, and web.pub.dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.




Introduction:

The below demo video shows how to implement on-tap vibration in Flutter and how a vibration will work using the HapticFeedback class and vibration package in your Flutter applications. We will show you when the user presses the button then, your device will vibrate. It will be shown on your device.

Demo Module::

Final Gif Output

Vibration Using HapticFeedback class:

In Flutter it is exceptionally simple to carry out vibration you should simply import Flutter services and use the hapticFeedback class.

import 'package:flutter/services.dart';

Note: If your device there is no Vibrator motor on mobile. This will not Work.

HapticFeedback Static Methods:

Allow access to haptic feedback on cell phones utilizing the underneath technique for the HapticFeedback class.
  • > vibrate — This method is utilized to provide vibration-haptic feedback to the user for a short duration.
  • > lightImpact —This method provides haptic feedback corresponding to a collision impact with a light mass.
  • > mediumImpact —This method provides haptic feedback corresponding to a collision impact with a medium mass.
  • > heavyImpact — This method provides haptic feedback corresponding to a collision impact with a heavy mass.
  • > selectionClick — This method is utilized to provide haptic feedback indication selection changing through discrete values.

In the body, we will make an ElevatedButton(). Inside the button, we will add the onPressed function. In this function, we will add HapticFeedback.heavyImpact(), also we will add the text “Vibrate Using HapticFeedback” on its child.

 ElevatedButton(
onPressed: () {
HapticFeedback.heavyImpact();
},
child: const Text("Vibrate Using HapticFeedback")),
When we run the application, we ought to get the screen’s output like the underneath screen capture.
Output

Vibration Using Vibration Package:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.
dependencies:
flutter:
sdk: flutter
vibration: ^1.8.4

Step 2: Import

import 'package:vibration/vibration.dart';

Step 3: Run flutter packages get in the root directory of your app.

Step 4: Add Vibration permission

Add the Vibration permission in android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.VIBRATE" />

Methods Of Vibration Package:

  • > hasVibrator — This method is utilized to check if the vibrator is available on the device.
  • > hasAmplitudeControl —This method is utilized to check if the vibrator has amplitude control in your device.
  • > hasCustomVibrationsSupport — This method is utilized to check if the device can vibrate with a custom duration, custom pattern, or custom intensities.

In the body, we will add the three ElevatedButtons() wrapped to it container. On the first button, we will add the default vibrate. But the default vibrate was 500ms and I was added 100ms. Also, we will check if the device has a vibration feature. On this second button, we will set the duration of the vibration was 2 sec means 2000ms.

 Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(5),
child: ElevatedButton(
child: const Text("Vibrate Default"),
onPressed: () async {
if (await Vibration.hasVibrator() != null) {
Vibration.vibrate(duration: 100);
}
},
),
),
Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(5),
child: ElevatedButton(
child: const Text("Vibrate For 2 Sec"),
onPressed: () {
Vibration.vibrate(duration: 2000);
},
),
),
Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(5),
child: ElevatedButton(
child: const Text("Vibrate With Pattern"),
onPressed: () {
Vibration.vibrate(pattern: [500, 1000, 500, 2000, 500, 3000]);
},
),
)

On the third button, we will vibrate with a pattern that means wait then vibrate again and repeat, etc. 500ms was waited, 1000ms vibrated, 500ms was waited, 2000ms, etc.

When we run the application, we ought to get the screen’s output like the underneath screen capture.
Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_vibration_demo/splash_screen.dart';
import 'package:vibration/vibration.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const Splash(),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () {
HapticFeedback.heavyImpact();
},
child: const Text("Vibrate Using HapticFeedback")),
const SizedBox(
height: 20,
),
Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(5),
child: ElevatedButton(
child: const Text("Vibrate Default"),
onPressed: () async {
if (await Vibration.hasVibrator() != null) {
Vibration.vibrate(duration: 100);
}
},
),
),
Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(5),
child: ElevatedButton(
child: const Text("Vibrate For 2 Sec"),
onPressed: () {
Vibration.vibrate(duration: 2000);
},
),
),
Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(5),
child: ElevatedButton(
child: const Text("Vibrate With Pattern"),
onPressed: () {
Vibration.vibrate(pattern: [500, 1000, 500, 2000, 500, 3000]);
},
),
)
],
),
),
);
}
}

Conclusion:

In the article, I have explained the Vibration in Flutter; you can modify this code according to your choice. This was a small introduction to the Vibration in Flutter User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying Vibration in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on the Vibration using the HapticFeedback class and vibration package in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.