Google search engine
Home Blog Page 72

Explore Sealed Classes In Dart

0

In this article, we will Explore Sealed Classes In Flutter. We perceive how to execute a demo program. We will show you what is a sealed classes? and how to use it in your 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::

What Is Sealed Classes?

Subclasses

Instances

Constructors

Switch Cases Expression Checking

Conclusion


What Is Sealed Classes?:

Sealed is a new modifier that was added in Dart 3. It can be applied to define a class or type with a restricted list of subtypes. We would like to create a class called Color, for instance. The Green, Blue, and Red classes are the only three that can be subtypes of the Color class.

Adding a sealed modifier to the Color class is the answer. The class cannot be expanded upon or used outside of its library with that modifier applied. Sealed classes are also inherently abstract.

Subclasses:

Every subclass needs to be defined in the same file, or the same library. An example of declaring the Color class and its subclasses is provided below.

sealed class Color {}

class Green extends Color {}

class Blue extends Color {}

class Red extends Color {
final String name;

Red(this.name);
}

The compiler will raise an error if you attempt to define a class in another file that extends the Color class.

class Item extends Color {}

Instances:

A sealed class’s constructor cannot be used to create an instance since it is implicitly abstract.

Color color = Color();

A sealed class’s subclasses are not inherently abstract. As a result, to create instances, you must use the constructor of the subclasses.

Green myGreen = Green();
Blue myBlue = Blue();
Red myRed = Red('flutterdevs.com');

Constructors:

Constructors defined by a sealed class are accessible to its subclasses. For instance, we add a field called id to the Color class mentioned above. A constructor exists that takes in the value of id. I included a print statement to make it simpler to determine whether the constructor is called when from the subclasses.

sealed class Color {

String id;

Color(this.id) {
print('Creating a color');
}
}

class Green extends Color {
Green(super.id);
}

class Blue extends Color {
Blue(super.id);
}

class Red extends Color {
final String name;

Red(String id, this.name) : super(id) {
print('Creating a red');
}
}

The ‘Creating a color’ text should appear when you attempt to create an instance of the subclass using the code mentioned above.

Additionally, some factory constructors can be defined.

sealed class Color {

String id;

Color(this.id) {
print('Creating a color');
}

factory Color.createByType(String type, String id) {
if (type == "green") {
return Green(id);
} else if (type == "blue") {
return Blue(id);
} else if (type == "red") {
return Red(id, 'flutterdevs.com');
}

throw UnsupportedError('Unknown type');
}
}

Switch Cases Expression Checking:

To determine whether an object is an instance of a specific class, you can construct a switch case in the Dart programming language. The compiler can notify you if a switch block isn’t handling every possible subtype because a sealed class has a known list of subtypes.

The switch block in the example below doesn’t handle the case in which the passed object is Red. Consequently, an error stating that the switch cases do not fully match the type will be displayed.

String getColorVoice(Color color) {
// ERROR: The type 'Color' is not exhaustively matched by the switch cases since it doesn't match 'Goat()'
return switch (color) {
Green() => 'light',
Blue() => 'dark',
};
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the Sealed Classes In Dart of your projects. If you want to define a class whose list of subtypes is predetermined and cannot be altered later, you should use Dart’s sealed modifier. The same library (file) must declare the list of subtypes.

Classes that are sealed cannot be instantiated and are implicitly abstract. You can, however, include factory constructors and other constructors. When you construct a switch block with a sealed class as the checked object type, the compiler can determine whether the switch cases have already exhaustively matched the type.

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


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.


Implement Audio Trimmer In Flutter

0

In this article, we will explore the Implement Audio Trimmer In Flutter. We perceive how to execute a demo program. We will show you how to trim audio files and save the trimmed audio files to the device utilizing the easy_audio_trimmer package in your Flutter applications.

  • For easy_audio_trimmer:

easy_audio_trimmer | Flutter Package
A Flutter package for trimming audio. This supports retrieving, trimming, and storing trimmed audio files in the…pub.dev

  • For file_picker:

file_picker | Flutter Package
A package that allows you to use a native file explorer to pick single or multiple absolute file paths, with extension…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:

An audio trimmer is an audio editor intended to cut, trim, or split audio parts. It permits you to eliminate undesirable parts from your audio clips and save the subsequent piece of the audio in different audio files organizations like MP3, WAV, AAC, FLAC, OGG, and WMA.

Audio trimmers fill a crucial need empowering clients to cut and refine audio cuts as per their inclinations. This usefulness tracks down applications in different situations, including making tweaked ringtones, altering, or just extricating important parts from extended recordings.

This demo video shows how to implement Audio Trimmer in Flutter and how Audio Trimmer will work using the easy_audio_trimmer package and in your Flutter applications. We will show you the simplest way to trim and save audio files on your device.

Demo Module::


Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
easy_audio_trimmer: ^1.0.2+4
file_picker: ^6.1.1

Step 2: Import

import 'package:easy_audio_trimmer/easy_audio_trimmer.dart';
import 'package:file_picker/file_picker.dart';

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

Step 4: While running on the Android platform if it gives an error that minSdkVersion needs to be 24, or on the iOS platform that the Podfile platform version should be 11

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 this dart file, we will create a new class AudioTrimmerDemo(). In this class, will add an ElevatedButton(). In this button, we will add the text “Select File” to its child function, and on the onPressed function, we will add the pick-up audio file function.

Center(
child: ElevatedButton(
style:
ElevatedButton.styleFrom(backgroundColor: Colors.teal.shade50),
onPressed: () async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.audio,
allowCompression: false,
);
if (result != null) {
File file = File(result.files.single.path!);
Navigator.of(context).push(
MaterialPageRoute(builder: (context) {
return AudioTrimmerViewDemo(file);
}),
);
}
},
child: const Text(
"Select File",
style: TextStyle(color: Colors.teal),
)),
),
When we run the application, we ought to get the screen’s output like the underneath screen capture.
Output

In the same dart file, we will create another new class AudioTrimmerViewDemo().

In this class, we will create a final Trimmer variable which is _trimmer is equal to Trimmer(). We will create two double variables _startValue and _endValue equal to 0.0. Also, we will create a three-bool variable was _isPlaying, _progressVisibility, and isLoading equal to false.

final Trimmer _trimmer = Trimmer();
double _startValue = 0.0;
double _endValue = 0.0;
bool _isPlaying = false;
bool _progressVisibility = false;
bool isLoading = false;

We will create an initState() method. In this method, we will add a _loadAudio() method. In this method, we will load the trimmer audio files.

@override
void initState() {
super.initState();
_loadAudio();
}
void _loadAudio() async {
setState(() {
isLoading = true;
});
await _trimmer.loadAudio(audioFile: widget.file);
setState(() {
isLoading = false;
});
}

We will create a _saveAudio method. In this method, we will save trimmed audio files.

_saveAudio() {
setState(() {
_progressVisibility = true;
});
_trimmer.saveTrimmedAudio(
startValue: _startValue,
endValue: _endValue,
audioFileName: DateTime.now().millisecondsSinceEpoch.toString(),
onSave: (outputPath) {
setState(() {
_progressVisibility = false;
});
debugPrint('OUTPUT PATH: $outputPath');
},
);
}

In the body part, we will create an audio trimmer view using the TrimViewer() method. In this method, we will set backgroundColor, barColor, viewerHeight, onChangeStart, etc.

Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TrimViewer(
trimmer: _trimmer,
viewerHeight: 100,
viewerWidth: MediaQuery.of(context).size.width,
durationStyle: DurationStyle.FORMAT_MM_SS,
backgroundColor:Colors.teal,
barColor: Colors.white,
durationTextStyle: const TextStyle(
color: Colors.teal),
allowAudioSelection: true,
editorProperties: const TrimEditorProperties(
circleSize: 10,
borderPaintColor: Colors.red,
borderWidth: 4,
borderRadius: 5,
circlePaintColor: Colors.redAccent,
),
areaProperties:
TrimAreaProperties.edgeBlur(blurEdges:true),
onChangeStart: (value) => _startValue = value,
onChangeEnd: (value) => _endValue = value,
onChangePlaybackState: (value) {
if (mounted) {
setState(() => _isPlaying = value);
}
},
),
),
),

Also, we will add the TextButton() method. In this method, we will add play and pause button functions.

TextButton(
child: _isPlaying
? const Icon(
Icons.pause,
size: 80.0,
color: Colors.teal,
)
: const Icon(
Icons.play_arrow,
size: 80.0,
color: Colors.teal,
),
onPressed: () async {
bool playbackState =
await _trimmer.audioPlaybackControl(
startValue: _startValue,
endValue: _endValue,
);
setState(() => _isPlaying = playbackState);
},
),

Also, we will add the Visibility() method. In this method, we will add LinearProgressIndicator(). This method will work on the save button only. When the user presses save the audio then the LinearProgressIndicator will be shown.

Visibility(
visible: _progressVisibility,
child: LinearProgressIndicator(
backgroundColor:
Theme.of(context).primaryColor.withOpacity(0.5),
),
),
ElevatedButton(
style:
ElevatedButton.styleFrom(backgroundColor: Colors.teal.shade50),
onPressed:
_progressVisibility ? null : () =>_saveAudio(),
child: const Text("SAVE",style: TextStyle(color: Colors.teal)),
),
When we run the application, we ought to get the screen’s output like the underneath screen capture.
Output

Code File:

import 'dart:io';
import 'package:easy_audio_trimmer/easy_audio_trimmer.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';

void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
home: AudioTrimmerDemo(),
);
}
}
class AudioTrimmerDemo extends StatefulWidget {
const AudioTrimmerDemo({super.key});
@override
State<AudioTrimmerDemo> createState() => _AudioTrimmerDemoState();
}
class _AudioTrimmerDemoState extends State<AudioTrimmerDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
centerTitle: true,
title: const Text(
"Flutter Audio Trimmer Demo",
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.teal,
),
body: Center(
child: ElevatedButton(
style:
ElevatedButton.styleFrom(backgroundColor: Colors.teal.shade50),
onPressed: () async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.audio,
allowCompression: false,
);
if (result != null) {
File file = File(result.files.single.path!);
Navigator.of(context).push(
MaterialPageRoute(builder: (context) {
return AudioTrimmerViewDemo(file);
}),
);
}
},
child: const Text(
"Select File",
style: TextStyle(color: Colors.teal),
)),
),
);
}
}
class AudioTrimmerViewDemo extends StatefulWidget {
final File file;
const AudioTrimmerViewDemo(this.file, {Key? key}) : super(key: key);
@override
State<AudioTrimmerViewDemo> createState() => _AudioTrimmerViewDemoState();
}
class _AudioTrimmerViewDemoState extends State<AudioTrimmerViewDemo> {
final Trimmer _trimmer = Trimmer();
double _startValue = 0.0;
double _endValue = 0.0;
bool _isPlaying = false;
bool _progressVisibility = false;
bool isLoading = false;
@override
void initState() {
super.initState();
_loadAudio();
}
void _loadAudio() async {
setState(() {
isLoading = true;
});
await _trimmer.loadAudio(audioFile: widget.file);
setState(() {
isLoading = false;
});
}
_saveAudio() {
setState(() {
_progressVisibility = true;
});
_trimmer.saveTrimmedAudio(
startValue: _startValue,
endValue: _endValue,
audioFileName: DateTime.now().millisecondsSinceEpoch.toString(),
onSave: (outputPath) {
setState(() {
_progressVisibility = false;
});
debugPrint('OUTPUT PATH: $outputPath');
},
);
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
if (Navigator.of(context).userGestureInProgress) {
return false;
} else {
return true;
}
},
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
title: const Text(
"Flutter Audio Trimmer Demo",
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.teal,
),
body: isLoading
? const Center(child: CircularProgressIndicator())
: Center(
child: Container(
padding: const EdgeInsets.only(bottom: 30.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TrimViewer(
trimmer: _trimmer,
viewerHeight: 100,
viewerWidth: MediaQuery.of(context).size.width,
durationStyle: DurationStyle.FORMAT_MM_SS,
backgroundColor:Colors.teal,
barColor: Colors.white,
durationTextStyle: const TextStyle(
color: Colors.teal),
allowAudioSelection: true,
editorProperties: const TrimEditorProperties(
circleSize: 10,
borderPaintColor: Colors.red,
borderWidth: 4,
borderRadius: 5,
circlePaintColor: Colors.redAccent,
),
areaProperties:
TrimAreaProperties.edgeBlur(blurEdges:true),
onChangeStart: (value) => _startValue = value,
onChangeEnd: (value) => _endValue = value,
onChangePlaybackState: (value) {
if (mounted) {
setState(() => _isPlaying = value);
}
},
),
),
),
TextButton(
child: _isPlaying
? const Icon(
Icons.pause,
size: 80.0,
color: Colors.teal,
)
: const Icon(
Icons.play_arrow,
size: 80.0,
color: Colors.teal,
),
onPressed: () async {
bool playbackState =
await _trimmer.audioPlaybackControl(
startValue: _startValue,
endValue: _endValue,
);
setState(() => _isPlaying = playbackState);
},
),
Visibility(
visible: _progressVisibility,
child: LinearProgressIndicator(
backgroundColor:
Theme.of(context).primaryColor.withOpacity(0.5),
),
),
ElevatedButton(
style:
ElevatedButton.styleFrom(backgroundColor: Colors.teal.shade50),
onPressed:
_progressVisibility ? null : () =>_saveAudio(),
child: const Text("SAVE",style: TextStyle(color: Colors.teal)),
),
],
),
),
),
),
);
}
}

Conclusion:

In the article, I have explained the Audio Trimmer In Flutter; you can modify this code according to your choice. This was a small introduction to the Audio Trimmer 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 the Audio Trimmer in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on Audio Trimmer 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.


Parallax Effect With PageView In Flutter

0

In this article, we will explore the Parallax Effect With PageView In Flutter. We see how to execute a demo program. Using a single background image scrolling in your Flutter applications, we will tell you how to create a parallax effect with pageview.

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

Code Implement

Code File

Conclusion



Introduction

The below demo video shows how to create a parallax effect with pageview in Flutter and how a parallax effect will work on pageview using a single background image in your Flutter applications. We will show a single image background scrolling using the parallax effect. It will be shown on your device.

Demo Module::


Code Implement:

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

In this class, we will add three parameters pageCount, screenSize, and offset. We will return the Sizebox with height and width and child we will add an image with alignment and fit.

class DataImage extends StatelessWidget {
  const DataImage({
    Key? key,
    required this.pageCount,
    required this.screenSize,
    required this.offset,
  }) : super(key: key);

  final Size screenSize;
  final int pageCount;
  final double offset;

  @override
  Widget build(BuildContext context) {
    int lastPageIdx = pageCount - 1;
    int firstPageIdx = 0;
    int alignmentMax = 1;
    int alignmentMin = -1;
    int pageRange = (lastPageIdx - firstPageIdx) - 1;
    int alignmentRange = (alignmentMax - alignmentMin);
    double alignment = (((offset - firstPageIdx) * alignmentRange) / pageRange) + alignmentMin;

    return SizedBox(
      height: screenSize.height,
      width: screenSize.width,
      child: Image(
        image: const AssetImage('assets/images/living_room.jpg'),
        alignment: Alignment(alignment, 0),
        fit: BoxFit.fitHeight,
      ),
    );
  }
}

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

In this class, we will add one parameter was string title. We will add a list of item variables was screens. We will add four data items.

class Item {
  const Item({required this.title,});
  final String title;
}

const List<Item> screens = [
  Item(title: 'Flower Pot',),
  Item(title: 'Chair',),
  Item(title: 'Wall Painting'),
  Item(title: 'Table', ),
  Item(title: 'Sofa',),
];

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

In the main .dart file. We will create a new class ParallaxDemo(). In this class, we will define a late PageController variable as _pageController and late double _pageOffset.

late PageController _pageController;
late double _pageOffset;

Now, we will create a dispose() method. in this method, we will add a variable of page Controller was _pageController.dispose().

@override
void dispose() {
_pageController.dispose();
super.dispose();
}
}

In the body, we will add a Stack widgte. in this widget. We will add a DataImage() class. In this class, we will add pageCount is screens.length+1, screenSize and offset is _pageOffset. Also we wii add a PageView() method. In this method, we will add controller is _pageController. In children, we will add items.map() navigate a column widget.

Stack(
        children: [
          DataImage(
            pageCount: items.length + 1,
            screenSize: MediaQuery.of(context).size,
            offset: _pageOffset,
          ),
          PageView(
            controller: _pageController,
            children: [
              ...items
                  .map((item) => Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    padding: const EdgeInsets.all(10),
                    color: Colors.black.withOpacity(0.7),
                    child: Text(
                      item.title,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 30,
                      ),
                    ),
                  ),

                ],
              ))
                  .toList(),
            ],
          ),
        ],
      ),

In this widget, we will add Container with the padding, color and its child we will add item.tittle.

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_parallax_effect_page_view_demo/splash_screen.dart';

void main() => runApp(const MyApp());

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

  @override
  Widget build(BuildContext context) => MaterialApp(
    debugShowCheckedModeBanner: false,
    theme: ThemeData(primarySwatch: Colors.blue),
    home: const Splash(),
  );
}

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

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

class _ParallaxDemoState extends State<ParallaxDemo> {
  late PageController _pageController;
  late double _pageOffset;

  @override
  void initState() {
    super.initState();
    _pageOffset = 0;
    _pageController = PageController(initialPage: 0);
    _pageController.addListener(
          () => setState(() => _pageOffset = _pageController.page ?? 0),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: const Text("Flutter Parallax Effect with PageView Demo",style: TextStyle(fontSize: 18),),
        backgroundColor: Colors.orange,
        centerTitle: true,
      ),
      body: Stack(
        children: [
          DataImage(
            pageCount: items.length + 1,
            screenSize: MediaQuery.of(context).size,
            offset: _pageOffset,
          ),
          PageView(
            controller: _pageController,
            children: [
              ...items
                  .map((item) => Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    padding: const EdgeInsets.all(10),
                    color: Colors.black.withOpacity(0.7),
                    child: Text(
                      item.title,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 30,
                      ),
                    ),
                  ),

                ],
              ))
                  .toList(),
            ],
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }
}

class DataImage extends StatelessWidget {
  const DataImage({
    Key? key,
    required this.pageCount,
    required this.screenSize,
    required this.offset,
  }) : super(key: key);

  final Size screenSize;
  final int pageCount;
  final double offset;

  @override
  Widget build(BuildContext context) {
    int lastPageIdx = pageCount - 1;
    int firstPageIdx = 0;
    int alignmentMax = 1;
    int alignmentMin = -1;
    int pageRange = (lastPageIdx - firstPageIdx) - 1;
    int alignmentRange = (alignmentMax - alignmentMin);
    double alignment = (((offset - firstPageIdx) * alignmentRange) / pageRange) + alignmentMin;

    return SizedBox(
      height: screenSize.height,
      width: screenSize.width,
      child: Image(
        image: const AssetImage('assets/images/living_room.jpg'),
        alignment: Alignment(alignment, 0),
        fit: BoxFit.fitHeight,
      ),
    );
  }
}

class Item {
  const Item({required this.title,});
  final String title;
}

const List<Item> items = [
  Item(title: 'Flower Pot',),
  Item(title: 'Chair',),
  Item(title: 'Wall Painting'),
  Item(title: 'Table', ),
  Item(title: 'Sofa',),
];

Conclusion:

In the article, I have explained the Parallax Effect With PageView in Flutter; you can modify this code according to your choice. This was a small introduction to the Parallax Effect With PageView 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 Parallax Effect With PageView in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on the Parallax Effect With PageView using the single background imge scrolling 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.


Custom Paint with Flutter

0

In this article, we will explore the Custom Paint with Flutter. We perceive how to execute a demo program. We will tell you the best way to create modified shapes, and sizes of the widgets using custom paint, and how to use it 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

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

CustomPaint is a widget that gives a material on which to draw during the paint stage. It essentially guarantees the UI planning of those parts that can’t be gotten from the ordinary shapes given by Flutter. This widget shows the adaptability of Flutter to its peers.

This demo ui shows how to create a customized shape in Flutter and how shapes will work using the custom paint widget in your Flutter applications. We will show you a two-draw shape of is circle and line on your device.

Demo Ui Module::

Final Output

Constructor:

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

CustomPaint({
super.key,
this.painter,
this.foregroundPainter,
this.size = Size.zero,
this.isComplex = false,
this.willChange = false,
super.child,
})

Properties:

There are some properties of CustomPaint:

  • > child: This property is used to the child holds whatever widget is needed to create the CustomPaint.
  • > foregroundPainter: This property is utilized by the painter who paints after the children. Likewise, it takes a class that extends the class CustomPaint.
  • > key: This property is used to control how one widget replaces another widget in the tree.
  • > painter: This property is utilized by the painter who paints before the child. Here you would have to make a class that extends the class CustomPaint.
  • > size: This property is used by the size of this CustomPaint, at first size is equivalent to Size.zero which implies if you don’t characterize a size or child, then the CustomPaint won’t show.
  • > willChange: This property is utilized to the whether the raster reserve ought to be informed that this painting is probably going to change in the following frame.

How to implement code in dart file :

You need to implement it in your code respectively:

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

To have the option to utilize the CustomPaint widget, you want to make a class that extends the CustomPaint. The class would need to execute two strategies paint() and shouldRepaint(). You can draw a circle by calling the strategy drawCircle() on the canvas object:

import 'package:flutter/material.dart';class CustomCircle extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint();
paint.color = Colors.teal.shade300;
paint.style = PaintingStyle.fill;
paint.strokeCap = StrokeCap.round;
paint.strokeJoin = StrokeJoin.round;Offset offset = Offset(size.width * 0.5, size.height);
canvas.drawCircle(offset, 50, paint);
}@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
}

If we check the code above, first, we are utilizing the Paint class, which is utilized to style the canvas. We furnished it with teal.shade300, the painting style is filled, strokeCap was round, strokeJoin was likewise round, offset we will add width and height. We call the strategy drawCircle and pass to it the contentions offset, 50, and paint.

We will pass the above method into a customPaint widget:

CustomPaint(
painter: CustomCircle(),
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.5,
height: MediaQuery.of(context).size.height * 0.1,
),
),
When we run the application, we ought to get the screen’s output like the underneath screen capture.
Output

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

To define a line alone, you want to likewise utilize the CustomPaint widget, and make another class CustomLine that extends the CustomPaint class. Here we likewise utilize the Paint object to style the CustomLine and we provide it with a width of 8. Then we want to make a starting point and an ending point that would be utilized to mirror the start of the line and the end.

import 'package:flutter/material.dart';class CustomLine extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint();
paint.color = Colors.teal;
paint.strokeWidth = 8;
paint.strokeCap = StrokeCap.round;Offset startingOffset = Offset(0, size.height);
Offset endingOffset = Offset(size.width, size.height);canvas.drawLine(startingOffset, endingOffset, paint);
}@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
}

In this way, we determine that the starting point should begin at the X-axis with coordinate 0 and the y-axis with the most extreme height while the endpoint should need to organize the greatest width as the X-axis and most extreme height as the y-axis consequently making a straight even line. We call the system drawLine and pass to it the disputes startingOffset, endingOffset, and paint.

Again we will pass the other above method into a customPaint widget:

CustomPaint(
painter: CustomLine(),
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.7,
height: MediaQuery.of(context).size.height * 0.08,
),
),
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_custom_paint/custom_circle.dart';
import 'package:flutter_custom_paint/custom_line.dart';void main() {
runApp(const MyApp());
}class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.green,
),
home: const CustomPaintDemo());
}
}class CustomPaintDemo extends StatefulWidget {
const CustomPaintDemo({Key? key}) : super(key: key);@override
_CustomPaintDemoState createState() => _CustomPaintDemoState();
}class _CustomPaintDemoState extends State<CustomPaintDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Custom Paint Demo"),
centerTitle: true,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: CustomPaint(
painter: CustomCircle(),
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.5,
height: MediaQuery.of(context).size.height * 0.1,
),
),
),
Center(
child: CustomPaint(
painter: CustomLine(),
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.7,
height: MediaQuery.of(context).size.height * 0.08,
),
),
),
],
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying Custom Paint in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on Custom Paint and how to create and use it 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.


OverlayPortal In Flutter

0

In this article, we will explore the OverlayPortal In Flutter. We perceive how to execute a demo program. We will tell you the best way to use OverlayPortal in your Flutter applications. It is another Flutter widget presented after Flutter version 3.10.

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

Code Implement

Code File

Conclusion



Introduction:

A widget that delivers its overlay child on an Overlay. The OverlayPortal utilizes overlayChildBuilder to construct its overlay child and renders it on the predetermined Overlay as though it was embedded utilizing an OverlayEntry, while it can rely upon a similar arrangement of InheritedWidgets like Theme that this widget can rely upon.

Demo Module::

The above demo video shows how to use OverlayPortal in Flutter and how OverlayPortal will work in your Flutter applications. We will show you images when the user taps on those images and then shows texts then again tap on those images texts will disappear. It will be shown on your device.

Constructor:

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

const OverlayPortal({
super.key,
required this.controller,
required this.overlayChildBuilder,
this.child,
})

Properties:

There are some properties of OverlayPortal:

  • > key — This property is used to control how one widget replaces another widget in the tree.
  • > controller — This property is utilized by the controller to show, hide, and bring to the top the overlay child.
  • > overlayChildBuilder — This property is utilized by the WidgetBuilder used to build a widget beneath this widget in the tree, that renders on the nearest Overlay.
  • > child — This property is used for the widget below this widget in the tree.

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 this dart file, we will create a new class OverlayPortalDemo(). In this class, we will create two final OverlayPortalControllers _overlayController and _overlayController1 equal to the OverlayPortalController().final OverlayPortalController _tooltipController = OverlayPortalController();
final OverlayPortalController _tooltipController1 = OverlayPortalController();

In the body part, we will return a Column widget. In this widget, we will add two TextButton widgets. In the first TextButton, we will add _overlayController.toggle on the onPressed method, In the child method we will add the OverlayPortal function. For this function, we will add _overlayController on the controller method, In the overlayChildBuilder method, we will return Positioned widget.

Column(
children: [
Expanded(
child: TextButton(
onPressed: _overlayController.toggle,
child: OverlayPortal(
controller: _overlayController,
overlayChildBuilder: (BuildContext context) {
return Positioned(
right: MediaQuery.of(context).size.width*0.22,
top: MediaQuery.of(context).size.height*0.42,
child: const ColoredBox(
color: Colors.black,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'FlutterDevs is a protruding flutter app\ndevelopment company',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
),
);
},
child: Image.asset(
'assets/logo.png',
height: 100,
),
),
),
),
Expanded(
child: TextButton(
onPressed: _overlayController1.toggle,
child: OverlayPortal(
controller: _overlayController1,
overlayChildBuilder: (BuildContext context) {
return Positioned(
right: MediaQuery.of(context).size.width*0.07,
bottom: MediaQuery.of(context).size.height*0.1,
child: const ColoredBox(
color: Colors.black,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'AeoLogic is a next generation digital transformation\ncompany that provides digital solutions',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
),
);
},
child: Image.asset(
'assets/powered_by.png',
height: 100,
),
),
),
),
],
)

In this Positioned widget, we will add text and wrap with the ColoredBox method. In the text button child method, we will add an image. When any user taps on this image then text will be shown on your devices with background color. Second text button all the methods will be the same except controller, image, and text will be changed.

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';

void main() => runApp(const MyApp());

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

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter OverlayPortal Demo'),
centerTitle: true,
backgroundColor: Colors.cyan,
),
body: const Center(child: OverlayPortalDemo()),
),
);
}
}

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

@override
State<StatefulWidget> createState() => OverlayPortalDemoState();
}

class OverlayPortalDemoState extends State<OverlayPortalDemo> {
final OverlayPortalController _overlayController = OverlayPortalController();
final OverlayPortalController _overlayController1 = OverlayPortalController();

@override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: TextButton(
onPressed: _overlayController.toggle,
child: OverlayPortal(
controller: _overlayController,
overlayChildBuilder: (BuildContext context) {
return Positioned(
right: MediaQuery.of(context).size.width*0.22,
top: MediaQuery.of(context).size.height*0.42,
child: const ColoredBox(
color: Colors.black,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'FlutterDevs is a protruding flutter app\ndevelopment company',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
),
);
},
child: Image.asset(
'assets/logo.png',
height: 100,
),
),
),
),
Expanded(
child: TextButton(
onPressed: _overlayController1.toggle,
child: OverlayPortal(
controller: _overlayController1,
overlayChildBuilder: (BuildContext context) {
return Positioned(
right: MediaQuery.of(context).size.width*0.07,
bottom: MediaQuery.of(context).size.height*0.1,
child: const ColoredBox(
color: Colors.black,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'AeoLogic is a next generation digital transformation\ncompany that provides digital solutions',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
),
);
},
child: Image.asset(
'assets/powered_by.png',
height: 100,
),
),
),
),
],
);
}
}

Conclusion:

In the article, I have explained the OverlayPortal in Flutter; you can modify this code according to your choice. This was a small introduction to the OverlayPortal 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 OverlayPortal in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on OverlayPortal and how to create and use it 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.


Socket Communication in Flutter: Building Real-time Apps

0

Welcome to the exciting world of Socket Communication in Flutter! In this blog, we’ll embark on a journey to explore the intricacies of building real-time apps using Flutter’s powerful socket programming capabilities. Uncover the secrets behind seamless data exchange between clients, and learn how to create dynamic, responsive applications that thrive on live updates and synchronized experiences.

Whether you’re a seasoned Flutter developer or just starting, this resource will equip you with the knowledge and skills to harness the full potential of socket communication and elevate your app development to new heights.

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 :

What are sockets?

Uses

Installation

Code Implementation

Final Output

GitHub Link

Reference Url

Conclusion


What are sockets?

Sockets are communication endpoints used to establish a connection between two computers or devices over a network. They facilitate bidirectional data flow, allowing processes on different machines to exchange information. Sockets provide a standard mechanism for processes running on separate devices to communicate, irrespective of the underlying hardware, operating systems, or programming languages.

There are two types of sockets:

  1. Server Socket: A server socket waits for incoming connections from clients. It listens on a specific port and, when a client attempts to connect, it establishes a communication channel with that client.
  2. Client Socket: A client socket initiates a connection to a server socket. It specifies the IP address and port of the server it wants to connect to. Once the connection is established, the client and server can exchange data.

Sockets are commonly used for various network applications, including web browsing, email communication, file transfers, and real-time applications such as online gaming and live chat.

In Flutter, the establishment of socket connections is made possible through different packages, with the web_socket_channel package emerging as a favored option among developers. The web_socket_channel package in Flutter serves as a valuable tool for incorporating WebSocket connections into applications. This package offers StreamChannel wrappers, ensuring compatibility across platforms. It provides a unified WebSocketChannel API, a versatile implementation communicating over a foundational StreamChannel. Additionally, it includes wrappers for both dart:io WebSocket class and dart:html WebSocket class, facilitating seamless integration for both server-side and client-side WebSocket communication.

Uses:-

Here are a few scenarios where web_socket_channel proves to be beneficial:

1. Real-time Communication: One of the key advantages of WebSocket channels is their ability to facilitate real-time communication. Traditional HTTP requests involve a request-response model, where the client sends a request to the server and awaits a response. In contrast, WebSocket channels enable a continuous, two-way flow of data, making them ideal for applications requiring instant updates and responsiveness.

2. Persistent Connection: Unlike HTTP, which relies on multiple request-response cycles, WebSocket channels maintain a persistent connection. Once established, this connection remains open, allowing for seamless and efficient data transmission between the client and server. This persistent connection minimizes latency and reduces the overhead associated with repeatedly establishing new connections.

3. Bi-Directional Data Flow: WebSocket channels support bi-directional data flow, meaning both the client and server can send data independently of each other. This bidirectional communication is invaluable for applications where real-time updates or instant notifications are essential, such as chat applications, live feeds, and collaborative tools.

4. Implementation with web_socket_channel: In Flutter, the web_socket_channel package simplifies the integration of WebSocket channels into applications. It provides a high-level API for creating WebSocket channels, sending and receiving messages, and handling connection events. By using the IOWebSocketChannel or HtmlWebSocketChannel, developers can seamlessly incorporate WebSocket functionality into both mobile and web applications.

5. Handling Messages with StreamBuilder: Flutter developers often leverage the widget to efficiently manage incoming data from a WebSocket channel. This widget allows for dynamic UI updates based on the data stream, ensuring the application’s interface reflects real-time changes. By combining WebSocket channels StreamBuilder, developers can create responsive and interactive user experiences. This is what we’re going to use in our below-demonstrating project.

6. Security Considerations: While WebSocket channels offer powerful capabilities, developers must be mindful of security considerations. Implementing secure WebSocket connections (wss://) with proper encryption helps protect sensitive data from potential threats. Additionally, ensuring that server-side WebSocket implementations adhere to best security practices is essential for safeguarding the overall application.

Let’s move further to a simple demonstrating project that will help you understand Websocket channels even more easily.

Installation:-

Add the `web_socket_channel` package to your `pubspec. yaml` file:

dependencies:
web_socket_channel: ^2.4.1

Run `flutter pub get` to install the package.

Code implementation:-

Below is the main.dart file of the project:

void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key});

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(
channel: IOWebSocketChannel.connect("ws://echo.websocket.org"),
),
);
}
}

As observed, we start by initializing our WebSocket channel at the outset. We utilize a convenient testing endpoint server, which is freely available for testing WebSocket and Server-Sent Events (SSE) clients effortlessly.

This server is specifically designed for testing HTTP proxies and clients, echoing details about HTTP request headers and bodies back to the client. It provides support for both WebSockets and server-sent events, simplifying the process of working with these technologies.

The endpoint is https://echo.websocket.org/

Here is the code snippet where we are actively streaming real-time data through the channel —

StreamBuilder(
stream: widget.channel.stream,
builder: (context, snapshot) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Center(
child: Stack(
children: [
BubbleWidget(
key: _bubbleKey,
text: snapshot.data ?? '',
),
],
),
));
},
)

WebSocket channel enables real-time data exchange, making it ideal for applications requiring instant updates, such as chat applications, live notifications, and collaborative editing. With web_socket_channel in Flutter, developers can easily implement WebSocket communication, ensuring efficient and responsive data transfer between the client and server in their applications. Exactly what we’re going to see in this project.

Let’s delve deeper. Here, we’ve got a function responsible for dispatching our messages to the WebSocket channel’s server —

void _sendMessage() {
if (textController.text.isNotEmpty) {
try {
widget.channel.sink.add(textController.text);
} catch (e) {
print("Error: $e");
}
setState(() {});
textController.clear();
}
}

We utilize a TextEditingController to capture user messages from the text field. These messages are then sent to our server through the WebSocket channel.

Hooray! Our project is done. Now, let’s examine the final output.

Final Output:-

After executing the demonstration project, we obtain…

GitHub Link:-

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


Reference Url:-

The Road to WebSockets
A look at how web technologies evolved since the inception of the World Wide `Web“, culminating with the emergence of…websocket.org

Conclusion:-

In this article, we’ve immersed ourselves in the realm of WebSockets, unraveling the complexities of real-time data streaming through web socket channels. I trust this exploration has been beneficial. Feel free to embark on your project to solidify your understanding of this technology.

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


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.