Google search engine
Home Blog Page 73

Implemented Segmented State Pattern In Flutter

In this article, we will explore the Segmented State Pattern. We will also implement a demo program and learn how to implement 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

Implementation

Conclusion

GitHub Link


Introduction:

First of all, I would like to introduce you to Segmented State Pattern.

Segmented State Pattern is a state management pattern in Flutter that uses Streams or ValueNotifiers. The Triple package is a simple package that uses this pattern.
State management is a critical aspect of building complex and interactive applications in Flutter. It helps you:

  • Control and update the data that your UI displays
  • Know about your application, where the user is in the app, what they are doing, and what data they are inputting
  • Align and integrate the core business logic inside the application with servers and databases
  • Ensure that the different parts of the application are working together predictably and consistently.

Implementation:

Let’s see how to Implement the Segmented State Pattern (Triple Pattern ).

First Add the dependencies in pubsec.yaml file

dependencies:
flutter_triple: ^3.0.0

Alright, now we will work on our store part for this. First of all, we will create a new file and call it counter_store.dart

import 'package:flutter_triple/flutter_triple.dart';

class CounterStore extends Store<int> with MementoMixin {
CounterStore() : super(0);

Future<void> increment() async {
setLoading(true);
await Future.delayed(const Duration(milliseconds: 1000));
update(state + 1);
setLoading(false);
}
}

Finally, we will design the Login Screen UI:

import 'package:flutter/material.dart';
import 'package:flutter_triple/flutter_triple.dart';
import 'counter_store.dart';

class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;

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

class MyHomePageState extends State<MyHomePage> {
final counter = CounterStore();
late Disposer disposer;

@override
void initState() {
super.initState();
disposer = counter.observer(onState: print);
}

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

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: [
IconButton(
onPressed: counter.undo,
icon: const Icon(Icons.arrow_back_ios),
),
IconButton(
onPressed: counter.redo,
icon: const Icon(Icons.arrow_forward_ios),
),
],
),
body: Center(
child: ScopedConsumer<CounterStore, int>(
store: counter,
onLoadingListener: (context, isLoading) {},
onErrorListener: (context, error) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(error.toString()),
),
);
},
onLoadingBuilder: (context) => const Text('Loading...'),
onStateBuilder: (context, state) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('You have pushed the button'),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'$state',
style: Theme.of(context).textTheme.headlineMedium,
),
const Text(
'Times',
),
],
),
],
);
},
),
),
floatingActionButton: TripleBuilder<CounterStore, int>(
store: counter,
builder: (context, triple) {
return FloatingActionButton(
onPressed: triple.isLoading ? null : counter.increment,
tooltip: triple.isLoading ? 'no-active' : 'Increment',
backgroundColor:
triple.isLoading ? Colors.grey : Theme.of(context).primaryColor,
child: const Icon(Icons.add),
);
},
),
);
}
}

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

Output

Conclusion:

In triple state management, onLoad Listener is an event that occurs when an object has been loaded. It’s often used within the body widget.

errorBuilder is a function that is executed when the task’s status is set to Error. It returns a widget that is called when the state is BaseErrorState.

loadingBuilder is a property that is a focused circular progress indicator until updating the counter value view on the screen. It allows you to customize the widget that’s displayed while the counter value increase action is performed


❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


GitHub Link:

You can check out Segmented State Pattern on GitHub. We hope you enjoyed this tutorial

GitHub – rahul-t-aeologic/triple_pattern_state_flutter_demo
Contribute to rahul-t-aeologic/triple_pattern_state_flutter_demo development by creating an account on GitHub.github.com


From Our Parent Company Aeologic

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

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

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

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

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


Implement Chart Export In Different Formats In Flutter

In this article, we will explore Chart Export in Different Formats. We will also implement a demo program and learn how to implement 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

Implementation

Conclusion

GitHub Link


Introduction:

A Flutter Charts library which includes data visualization widgets such as bar charts, circular charts, and line charts, to create real-time, interactive, high-performance, animated charts.

To render a Flutter chart utilizing JSON data, you can utilize the deserialization idea. This includes changing the JSON data over completely to a Dart list object. You can then utilize the deserialized list object as chart data for a Flutter Cartesian chart.

Here are some ways to export charts in Flutter:
  • > SfCartesianChart: Exports Cartesian charts as PNG images or PDF documents
  • > Syncfusion’s Flutter DataGrid export library: Exports Flutter DataGrids to Excel and PDF formats

Implementation:

Let’s see how to Implement Chart Rendering in Different Formats.

First Add the dependencies in pubsec.yaml file
dependencies:
syncfusion_flutter_charts: ^22.2.8

Alright, now we will work on further implementation for:

> Bar Chart

> Line Chart

> Pie Chart

First Add the dependencies in pubsec.yaml file
path_provider: ^2.1.0
open_file: ^3.3.2
syncfusion_flutter_pdf: ^22.2.12
syncfusion_flutter_xlsio:

Now we will design the Home Screen UI:

Bar Chart:

We will create a new class BarChartView() class. In this class, we will add barChartData is equal to the array bracket. In the body part, we will add a column widget. In this widget, we will add the BarChartViewWidget() method.

import 'package:flutter/material.dart';
import 'package:render_chart_and_chart_data_in_multiple_form/widgets/custom_button.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

import '../constants/app_text_style.dart';
import '../constants/color_constants.dart';
import '../constants/dimension_constants.dart';
import '../helper/app_helper.dart';
import '../helper/size_helper.dart';
import '../model/bar_chart_data_model.dart';
import '../resources/assets.gen.dart';
import '../widgets/bar_chart_view_widget.dart';

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

@override
State<BarChartView> createState() => _BarChartViewState();
}

class _BarChartViewState extends State<BarChartView> {
List<BarChartDataModel> barChartData = [];
bool isLoading = false;
late GlobalKey<SfCartesianChartState> barChartKey;
late TooltipBehavior barChartToolTipBehavior;

_initializeData() async {
setState(() {
isLoading = true;
});

barChartData = [
(BarChartDataModel(x: '1', y1: 5, y2: 11, y3: 15, y4: 8)),
(BarChartDataModel(x: '2', y1: 15, y2: 17, y3: 8, y4: 2)),
(BarChartDataModel(x: '3', y1: 20, y2: 18, y3: 9, y4: 6)),
(BarChartDataModel(x: '4', y1: 8, y2: 9, y3: 2, y4: 10)),
(BarChartDataModel(x: '5', y1: 15, y2: 9, y3: 7, y4: 4))
];
await Future.delayed(const Duration(seconds: 1));
setState(() {
isLoading = false;
});
}

@override
initState() {
barChartKey = GlobalKey();
barChartToolTipBehavior = TooltipBehavior(
enable: true,
tooltipPosition: TooltipPosition.pointer,
);
_initializeData();
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: const Icon(
Icons.arrow_back_ios_new,
color: ColorConstants.radicalRed,
),
),
title: Text('Bar Chart Demo',
style: AppTextStyles.boldText(
fontSize: Dimensions.px20, color: ColorConstants.radicalRed)),
),
body: isLoading
? const Center(
child: CircularProgressIndicator(
color: ColorConstants.radicalRed,
),
)
: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Dimensions.px10, vertical: Dimensions.px10),
child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
children: [
BarChartViewWidget(
maximumPoint: Dimensions.px60,
intervalPoint: Dimensions.px10,
key: barChartKey,
chartData: barChartData,
toolTip: barChartToolTipBehavior,
),
SizeHelper.h2(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Download as',
style: AppTextStyles.boldText(
fontSize: Dimensions.px22,
color: ColorConstants.radicalRed),
),
MyAssets.download.svg(),
],
),
SizeHelper.h2(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Expanded(
child: CustomButton(
onTap: () {
AppHelper.getRenderChartAsImage(barChartKey, false);
},
label: 'PNG Image',
style: AppTextStyles.semiBoldText(
fontSize: Dimensions.px16,
color: ColorConstants.white),
iconWidget: MyAssets.png_file.svg(),
),
),
SizeHelper.w2(),
Expanded(
child: CustomButton(
onTap: () {
AppHelper.getRenderPDF(barChartKey, false);
},
label: 'PDF File',
style: AppTextStyles.semiBoldText(
fontSize: Dimensions.px16,
color: ColorConstants.white),
iconWidget: MyAssets.pdf_file.svg(),
),
),
],
),
SizeHelper.h1(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Expanded(
child: CustomButton(
onTap: () {
AppHelper.getRenderChartAsExcel(
barChartData, false);
},
label: 'Excel (xls)',
style: AppTextStyles.semiBoldText(
fontSize: Dimensions.px16,
color: ColorConstants.white),
iconWidget: MyAssets.xls_file.svg(),
),
),
],
),
],
),
),
);
}
}

In this method, we will add maximumPoint, intervalPoint, key, chartData, and toolTip. Now we will add three custom buttons PNG Image, PDF File, and Excel (xls) for the download bar chart in these formats.

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

Line Chart:

We will create a new class LineChartView() class. In this class, we will add lineChartData is equal to the array bracket. In the body part, we will add a column widget. In this widget, we will add the LineChartViewWidget() method.

import 'package:flutter/material.dart';
import 'package:render_chart_and_chart_data_in_multiple_form/model/line_chart_data_model.dart';
import 'package:render_chart_and_chart_data_in_multiple_form/widgets/custom_button.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

import '../constants/app_text_style.dart';
import '../constants/color_constants.dart';
import '../constants/dimension_constants.dart';
import '../helper/app_helper.dart';
import '../helper/size_helper.dart';
import '../resources/assets.gen.dart';
import '../widgets/line_chart_view_widget.dart';

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

@override
State<LineChartView> createState() => _LineChartViewState();
}

class _LineChartViewState extends State<LineChartView> {
List<LineChartDataModel> lineChartData = [];
bool isLoading = false;
late GlobalKey<SfCartesianChartState> lineChartKey;
late TooltipBehavior lineChartToolTipBehavior;

_initializeData() async {
setState(() {
isLoading = true;
});

lineChartData = [
(LineChartDataModel(x: 'Jan', y: 10)),
(LineChartDataModel(x: 'Fab', y: 40)),
(LineChartDataModel(x: 'Mar', y: 30)),
(LineChartDataModel(x: 'Apr', y: 50)),
(LineChartDataModel(x: 'May', y: 5)),
];
await Future.delayed(const Duration(seconds: 1));
setState(() {
isLoading = false;
});
}

@override
initState() {
lineChartKey = GlobalKey();
lineChartToolTipBehavior = TooltipBehavior(
enable: true,
);
_initializeData();
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: const Icon(
Icons.arrow_back_ios_new,
color: ColorConstants.radicalRed,
),
),
title: Text('Line Chart Demo',
style: AppTextStyles.boldText(
fontSize: Dimensions.px20, color: ColorConstants.radicalRed)),
),
body: isLoading
? const Center(
child: CircularProgressIndicator(
color: ColorConstants.radicalRed,
),
)
: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Dimensions.px10, vertical: Dimensions.px10),
child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
children: [
LineChartViewWidget(
maximumPoint: Dimensions.px60,
intervalPoint: Dimensions.px10,
key: lineChartKey,
lineChartData: lineChartData,
toolTip: lineChartToolTipBehavior,
),
SizeHelper.h2(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Download as',
style: AppTextStyles.boldText(
fontSize: Dimensions.px22,
color: ColorConstants.radicalRed),
),
MyAssets.download.svg(),
],
),
SizeHelper.h2(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Expanded(
child: CustomButton(
onTap: () {
AppHelper.getRenderChartAsImage(
lineChartKey, false);
},
label: 'PNG Image',
style: AppTextStyles.semiBoldText(
fontSize: Dimensions.px16,
color: ColorConstants.white),
iconWidget: MyAssets.png_file.svg(),
),
),
SizeHelper.w2(),
Expanded(
child: CustomButton(
onTap: () {
AppHelper.getRenderPDF(lineChartKey, false);
},
label: 'PDF File',
style: AppTextStyles.semiBoldText(
fontSize: Dimensions.px16,
color: ColorConstants.white),
iconWidget: MyAssets.pdf_file.svg(),
),
),
],
),
SizeHelper.h1(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Expanded(
child: CustomButton(
onTap: () {
AppHelper.getRenderChartAsExcel(
lineChartData, true);
},
label: 'Excel (xls)',
style: AppTextStyles.semiBoldText(
fontSize: Dimensions.px16,
color: ColorConstants.white),
iconWidget: MyAssets.xls_file.svg(),
),
),
],
),
],
),
),
);
}
}

In this method, we will add maximumPoint, intervalPoint, key, linechartData, and toolTip. Same as above we will add three custom buttons PNG Image, PDF File, and Excel (xls) for the download line chart in these formats.

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

Pie Chart:

We will create a new class PieChartView() class. In this class, we will add pieChartData is equal to the array bracket. In the body part, we will add a column widget. In this widget, we will add the RepaintBoundary() method.

import 'package:flutter/material.dart';
import 'package:render_chart_and_chart_data_in_multiple_form/widgets/custom_button.dart';

import '../constants/app_text_style.dart';
import '../constants/color_constants.dart';
import '../constants/dimension_constants.dart';
import '../helper/app_helper.dart';
import '../helper/size_helper.dart';
import '../model/pie_chart_data_model.dart';
import '../resources/assets.gen.dart';
import '../widgets/pie_chart_view_widget.dart';

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

@override
State<PieChartView> createState() => _PieChartViewState();
}

class _PieChartViewState extends State<PieChartView> {
List<PieChartDataModel> pieChartData = [];
bool isLoading = false;
late GlobalKey pieChartKey;

_initializeData() async {
setState(() {
isLoading = true;
});

pieChartData = [
(PieChartDataModel(
x: 'Jan',
y: 15,
z: ColorConstants.radicalRed,
)),
(PieChartDataModel(
x: 'Fab',
y: 10,
z: ColorConstants.purple,
)),
(PieChartDataModel(
x: 'Mar',
y: 20,
z: ColorConstants.semiGrey,
)),
(PieChartDataModel(
x: 'Apr',
y: 20,
z: ColorConstants.laPalma,
)),
(PieChartDataModel(
x: 'May',
y: 20,
z: ColorConstants.grey,
)),
];
await Future.delayed(const Duration(seconds: 1));
setState(() {
isLoading = false;
});
}

@override
initState() {
pieChartKey = GlobalKey();
_initializeData();
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: const Icon(
Icons.arrow_back_ios_new,
color: ColorConstants.radicalRed,
),
),
title: Text('Pie Chart Demo',
style: AppTextStyles.boldText(
fontSize: Dimensions.px20, color: ColorConstants.radicalRed)),
),
body: isLoading
? const Center(
child: CircularProgressIndicator(
color: ColorConstants.radicalRed,
),
)
: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Dimensions.px10, vertical: Dimensions.px10),
child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
children: [
RepaintBoundary(
key: pieChartKey,
child: PieChartViewWidget(pieChartData: pieChartData),
),
SizeHelper.h2(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Download as',
style: AppTextStyles.boldText(
fontSize: Dimensions.px22,
color: ColorConstants.radicalRed),
),
MyAssets.download.svg(),
],
),
SizeHelper.h2(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Expanded(
child: CustomButton(
onTap: () {
AppHelper.getRenderChartAsImage(pieChartKey, true);
},
label: 'PNG Image',
style: AppTextStyles.semiBoldText(
fontSize: Dimensions.px16,
color: ColorConstants.white),
iconWidget: MyAssets.png_file.svg(),
),
),
SizeHelper.w2(),
Expanded(
child: CustomButton(
onTap: () {
AppHelper.getRenderPDF(pieChartKey, true);
},
label: 'PDF File',
style: AppTextStyles.semiBoldText(
fontSize: Dimensions.px16,
color: ColorConstants.white),
iconWidget: MyAssets.pdf_file.svg(),
),
),
],
),
SizeHelper.h1(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Expanded(
child: CustomButton(
onTap: () {
AppHelper.getRenderChartAsExcel(pieChartData, true);
},
label: 'Excel (xls)',
style: AppTextStyles.semiBoldText(
fontSize: Dimensions.px16,
color: ColorConstants.white),
iconWidget: MyAssets.xls_file.svg(),
),
),
],
),
],
),
),
);
}
}

In this method, we will add a key and a child. In child was PieChartViewWidget(pieChartData: pieChartData) . Same as above we will add three custom buttons PNG Image, PDF File, and Excel (xls) for the download line chart in these formats.

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

Pie Chart Output

Alright, now we will implement the download Functionality part:

> Export in PNG format

> Export in PDF format

> Export in Excel (.xls) format

Export in PNG Format:

We will create getRenderChartAsImage() method:

static Future<void> getRenderChartAsImage(
dynamic cartesianChartKey, bool isPieChart) async {
final Directory directory = await getApplicationSupportDirectory();
final String path = directory.path;
File file = File('$path/ChartImageOutput.png');
if (isPieChart) {
final RenderRepaintBoundary boundary =
cartesianChartKey.currentContext.findRenderObject();

final ui.Image image = await boundary.toImage();

final ByteData? byteData =
await image.toByteData(format: ui.ImageByteFormat.png);

final Uint8List? pngBytes = byteData?.buffer.asUint8List();
final Uint8List imageBytes = pngBytes!.buffer
.asUint8List(pngBytes.offsetInBytes, pngBytes.lengthInBytes);
await file.writeAsBytes(imageBytes, flush: true);
} else {
final ui.Image data =
await cartesianChartKey.currentState!.toImage(pixelRatio: 3.0);
final ByteData? bytes =
await data.toByteData(format: ui.ImageByteFormat.png);
final Uint8List imageBytes =
bytes!.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes);
await file.writeAsBytes(imageBytes, flush: true);
}

OpenFile.open('$path/ChartImageOutput.png');
}

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

Output

Export in PDF Format:

We will create getRenderPDF() method:

static Future<void> getRenderPDF(
dynamic cartesianChartKey, isPieChart) async {
final Directory directory = await getApplicationSupportDirectory();
final String path = directory.path;
File file = File('$path/ChartPdfOutput.pdf');
final List<int> imageBytes =
await _readImageData(cartesianChartKey, isPieChart);
final PdfBitmap bitmap = PdfBitmap(imageBytes);
final PdfDocument document = PdfDocument();
if (isPieChart) {
document.pageSettings.orientation = PdfPageOrientation.landscape;
}

document.pageSettings.size =
Size(bitmap.width.toDouble(), bitmap.height.toDouble());
final PdfPage page = document.pages.add();
final Size pageSize = page.getClientSize();
page.graphics.drawImage(
bitmap, Rect.fromLTWH(0, 0, pageSize.width, pageSize.height));
final List<int> bytes = document.saveSync();
document.dispose();

await file.writeAsBytes(bytes, flush: true);
OpenFile.open('$path/ChartPdfOutput.pdf');
}

We will create _readImageData() method:

static Future<List<int>> _readImageData(cartesianChartKey, isPieChart) async {
if (isPieChart) {
final RenderRepaintBoundary boundary =
cartesianChartKey.currentContext.findRenderObject();

final ui.Image image = await boundary.toImage();

final ByteData? byteData =
await image.toByteData(format: ui.ImageByteFormat.png);

final Uint8List? pngBytes = byteData?.buffer.asUint8List();
return pngBytes!.buffer
.asUint8List(pngBytes.offsetInBytes, pngBytes.lengthInBytes);
} else {
final ui.Image data =
await cartesianChartKey.currentState!.toImage(pixelRatio: 3.0);
final ByteData? bytes =
await data.toByteData(format: ui.ImageByteFormat.png);

return bytes!.buffer
.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes);
}
}

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

Output

Export in Excel (.xls) Format:

We will create getRenderChartAsExcel() method:

static Future<void> getRenderChartAsExcel(
List<dynamic> data, bool isLineChart) async {
final Directory directory = await getApplicationSupportDirectory();
final String path = directory.path;
final xcel.Workbook workbook = xcel.Workbook();
final xcel.Worksheet sheet = workbook.worksheets[0];

if (!isLineChart) {
sheet.getRangeByIndex(1, 1).setText("Sr.");
sheet.getRangeByIndex(1, 2).setText("Pending");
sheet.getRangeByIndex(1, 3).setText("Resolve-Requested");
sheet.getRangeByIndex(1, 4).setText("Resolve");
sheet.getRangeByIndex(1, 5).setText("Closed");
sheet.autoFitColumn(3);

for (var i = 0; i < data.length; i++) {
final item = data[i];
sheet.getRangeByIndex(i + 2, 1).setText(item.x);
sheet.getRangeByIndex(i + 2, 2).setText(item.y1.toString());
sheet.getRangeByIndex(i + 2, 3).setText(item.y2.toString());
sheet.getRangeByIndex(i + 2, 4).setText(item.y3.toString());
sheet.getRangeByIndex(i + 2, 5).setText(item.y4.toString());
}
final List<int> bytes = workbook.saveAsStream();
File file = File('$path/BarChartOutput.xlsx');
await file.writeAsBytes(bytes, flush: true);

await OpenFile.open('$path/BarChartOutput.xlsx');
AppLogger.log('data list :${file.lengthSync()}');
} else {
sheet.getRangeByIndex(1, 1).setText("Month");
sheet.getRangeByIndex(1, 2).setText(" Value ");
sheet.autoFitColumn(2);

for (var i = 0; i < data.length; i++) {
final item = data[i];
sheet.getRangeByIndex(i + 2, 1).setText(item.x);
sheet.getRangeByIndex(i + 2, 2).setText(item.y.toString());
}
final List<int> bytes = workbook.saveAsStream();
File file = File('$path/LineChartOutput.xlsx');
await file.writeAsBytes(bytes, flush: true);

await OpenFile.open('$path/LineChartOutput.xlsx');
}
workbook.dispose();
}

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

Output

Conclusion:

In the article, I have explained the Chart Export in Different Formats In Flutter; you can modify this code according to your choice. This was a small introduction to the Chart Export in Different Formats 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 Chart Export in Different Formats in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on chart export in different formats in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


GitHub Link:

You can check out Implement Chart Export in Different Formats In Flutter on GitHub. We hope you enjoyed this tutorial

GitHub — rahul-t-aeologic/render_chart_and_chart_data_in_multiple_form: Implement Chart Rendering…
Implement Chart Rendering in Different Formats. Contribute to…github.com


From Our Parent Company Aeologic

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

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

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

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

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


Implement Fish-Redux State Management In Flutter

In this article, we will explore the Implement Fish-Redux State Management In Flutter. We perceive how to execute a demo program. We will show you how to work in your Flutter applications.

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


Table of Contents :

Introduction — State Management in Flutter

Introduction — Fish-Redux state management

Key-concepts in Fish-Redux

How to use

Key Benefits

Final Output

GitHub Link

Reference Url

Conclusion


Introduction — State management:-

State management in Flutter refers to the techniques and tools used to manage and control the state (data and UI) of your Flutter application. Flutter applications often consist of complex UIs and dynamic data that can change over time.

Effective state management is crucial for creating responsive and maintainable apps. There are various approaches to state management in Flutter, and the choice of approach depends on the complexity of your application and your specific needs.

Introduction — Fish-Redux:-

Fish-Redux is a state management framework for building Flutter applications. It’s designed to help Flutter developers structure their applications in a way that makes code organization and maintenance easier, particularly for larger and more complex apps. Fish-Redux draws inspiration from concepts like Redux, a state management pattern used in web development, and applies them to the world of Flutter.

Key Concepts in Fish-Redux:-

  • State: In Fish-Redux, your application’s state is represented by plain Dart objects. These objects are typically immutable and describe the data that your application needs to function. State management in Fish-Redux revolves around creating, modifying, and sharing these state objects.
  • Action: Actions are the events or user interactions that trigger changes in your application’s state. Actions are dispatched to update the state. They carry information about what needs to change in the state.
  • Reducer: Reducers are responsible for taking the current state and an action and producing a new state. Reducers are pure functions that ensure the predictability and maintainability of the state management process.
  • Effect: Effects are side effects that can be triggered as a result of specific actions. They can be used for operations like making network requests, database access, or other asynchronous tasks. Fish-Redux provides a clean way to handle side effects.
  • Component: A component is a self-contained, reusable piece of the user interface. Each component in Fish-Redux consists of three parts: View, State, and Reducer. Components can be nested to build complex UI structures.
  • Page: A page in Fish-Redux is a logical collection of components. Pages help organize your app into meaningful sections. Each page has its state and can contain multiple components.

How to Use:-

Here are the basic steps to use Fish-Redux in your Flutter application:

  • Add Fish-Redux Dependency: Start by adding the Fish-Redux package as a dependency in your pubspec.yaml file:
dependencies:
fish_redux: ^0.3.7 # Use the latest compatible version
  • Define the Application State: Create a Dart class that represents the state of your application. This class should extend Cloneable. Define the properties and initial values for your application’s state.
Example:
import 'package:fish_redux/fish_redux.dart';

class CounterState implements Cloneable<CounterState> {
int count;
@override
CounterState clone() {
return CounterState()..count = count;
}
}
  • Define Actions: Create action classes that describe the events or user interactions that can change the state. Actions should include all the necessary data for the change.
Example:
import 'package:fish_redux/fish_redux.dart';

enum CounterAction { increment, decrement }
class CounterActionCreator {
static Action increment() {
return const Action(CounterAction.increment);
}
static Action decrement() {
return const Action(CounterAction.decrement);
}
}
  • Create Reducers: Write reducer functions that take the current state and an action as input and produce a new state as output. Reducers should be pure functions.
Example:
import 'action.dart';
import 'state.dart';

CounterState reducer(CounterState state, Action action) {
final CounterState newState = state.clone();
if (action.type == CounterAction.increment) {
newState.count += 1;
} else if (action.type == CounterAction.decrement) {
newState.count -= 1;
}
return newState;
}
  • Build Components: Create individual components for your UI. Each component includes a View (widget), State (describing the component’s local state), and Reducer (defining how to update the local state).
Example:
import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart';

import 'state.dart';
Widget buildView(CounterState state, Dispatch dispatch, ViewService viewService) {
return Scaffold(
appBar: AppBar(
title: Text('Fish Redux Counter Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Counter Value:',
style: TextStyle(fontSize: 20),
),
Text(
'${state.count}',
style: TextStyle(fontSize: 36, color: Colors.blue),
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.remove),
onPressed: () => dispatch(CounterActionCreator.decrement()),
),
IconButton(
icon: Icon(Icons.add),
onPressed: () => dispatch(CounterActionCreator.increment()),
),
],
),
],
),
),
);
}
  • Define Pages: Organize your components into pages. Each page has its state and can contain multiple components.
  • Initialize the Fish-Redux Store: Create a Store that holds the global application state, reducers, and middleware. This is the central hub for state management.
Example:
import 'package:fish_redux/fish_redux.dart';

import 'reducer.dart';
import 'state.dart';
Store<CounterState> createStore() {
return Store<CounterState>(
initialState: CounterState()..count = 0,
reducer: counterReducer,
);
}
  • Dispatch Actions: To update the state, dispatch actions to the store. The store will invoke the reducers to calculate the new state.
  • Build the UI: Use the components and pages to build the user interface. Components are generally built by buildView methods.
  • Handle Effects: For side effects like making API requests or accessing databases, use Effects to encapsulate the logic.

Fish-Redux provides a structured and organized way to manage the state of your Flutter application, making it easier to build and maintain large and complex apps.

Key Benefits:-

  • Centralized and Observable Data Management: Fish Redux simplifies data management by centralizing it through Redux. This means it retains all the advantages of Redux, and the framework even assembles the reducer automatically, making Redux usage more straightforward.
  • Component Division Management: Fish Redux divides views and data into components. By breaking down complex pages and data into smaller, independent modules, collaborative development within teams becomes much easier.
  • Isolation Between View, Effect, and Reducer: Each component is divided into three stateless and independent functions: View, Effect, and Reducer. Their statelessness makes them easy to write, debug, test, and maintain. This also allows for more flexibility in combining, reusing, and innovating.
  • Declarative Configuration Assemblies: Components and adapters are put together using free and declarative configuration, which includes defining a component’s view, reducer, effect, and its relationships with dependent child components.
  • Strong Scalability: The core framework focuses on its core responsibilities while providing flexibility for upper layers. While the framework itself doesn’t contain printed code, it allows observation of data flows and component changes through standard middleware. Additionally, mixins can be added to the component and adapter layers using Dart code, enhancing customizability and capabilities at the upper layer. The framework seamlessly communicates with other middlewares, such as those for automatic exposure and high availability, and allows for free assembly by the upper layer.
  • Small, Simple, and Complete: Fish Redux is incredibly lightweight, consisting of only around 1,000 lines of code. It’s user-friendly, requiring just a few small functions to set up before running. Despite its simplicity, Fish Redux provides a wide range of functionalities.

There’s a simple demo app below using fish-redux state management. Check the GitHub repo in the GitHub Link section.

Output:-

After running the demo project, we get

GitHub Link:-

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


Reference Url:-

Flutter Analysis and Practice: App Framework Design Practices
This article describes the features and usage of Fish Redux for Xianyu’s application.alibaba-cloud.medium.com


Conclusion:-

This blog has provided a comprehensive understanding of Fish-Redux state management in Flutter applications. Now, you have the knowledge and tools to apply this powerful state management solution to your projects and explore the wide range of possibilities it offers. Enjoy your journey of exploration and development!

❤ ❤ 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 PostgreSQL In Flutter

0

Hello Everyone!!! Today we learn about PostgreSQL With Flutter In this article, we cover topics like how to set up PostgreSQL and also how we can use PostgreSQL With Flutter.


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 of PostgreSQL

PostgreSQL Setup Steps

Add Dependency

Configuration

Conclusion

GitHub Link


Introduction of PostgreSQL:

PostgreSQL is a powerful, open-source object-relational database system. It has more than 15 years of active development phase and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness.

PostgreSQL (pronounced as post-gress-Q-L) is an open-source relational database management system (DBMS) developed by a worldwide team of volunteers. PostgreSQL is not controlled by any corporation or other private entity and the source code is available free of charge.

PostgreSQL Setup Steps:

  • Downloading the installer
  • Launching the installation
  • Selecting the install location
  • Selecting components
  • Selecting where to store data
  • Setting the user password
  • Selecting the port number
  • Setting locale
  • Review and installation

1. Downloading the installer

Visit the downloads page of EnterpriseDB’s website, https://www.enterprisedb.com/downloads/postgres-postgresql-downloads. Download your preferred version from the list available.

2. Launching the installation

Run the downloaded dmg package as the administrator user. When you get the screen below, click on the “Next” button:

3. Selecting the install location

You will be asked to specify which directory you wish to use to install Postgres. Select your desired location and click “Next”:

4. Selecting components

You will next be asked to select the tools that you want to install along with the Postgres installation. PostgreSQL server and command line tools are compulsory. Stack Builder and pgAdmin 4 are optional. Please select from the list and click “Next”:

5. Selecting where to store data

You will be asked to select the location for your Postgres cluster’s Data Directory. Please select an appropriate location and click “Next”:

6. Setting the superuser password

You will be asked to provide the password of the Postgres Unix superuser, which will be created at the time of installation. Please provide an appropriate password and click “Next”:

7. Selecting the port number

You will be asked to select the port number on which the PostgreSQL server will listen for incoming connections. Please provide an appropriate port number. (The default port number is 5432.) Make sure the port is open from your firewall and the traffic on that port is accessible. Click “Next”:

8. Setting locale

Please select the appropriate locale (language preferences) and click “Next”:

9. Review and installation

You will be provided a summary of your selections from the previous installation screens. Review it carefully and click “Next” to complete the installation:

Add Dependency:

Run this command:

With Dart:

$ dart pub add postgres

With Flutter:

$ flutter pub add postgres

This will add a line like this to your package’s pubspec.yaml (and run an implicit dart pub get):

dependencies:
postgres: ^2.6.1

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:postgres/postgres.dart';

Configuration:

Create PostgreSQLConnection and open them:

static var connection = PostgreSQLConnection(
Constants.dbHostForEmulator, Constants.port, Constants.db,
username: Constants.dbUsername, password: Constants.dbPassword);
static Future<void> requestForDBConnectionStart() async {
await connection.open().then((value) => debugPrint("Connection Establish"));
}

Execute queries with query:

Queries for Creating Tablestatic Future<String?> createTable() async{
try {
await connection.query('''
CREATE TABLE person(
name text,
email text
)
''').then((value) => (){
return "table created successfully";
});
} on PostgreSQLException catch (e) {
print(e.message);
return e.message;
}
return "";
}

Queries for Insert data in the table

static Future<void> addData() async {
try {
await connection.query('''
INSERT INTO person(name,email)
VALUES ('RAHUL THAKUR','rahul@oppong.co')
''');
} on PostgreSQLException catch (e) {
print(e.message);
}
}

Queries for fetching all data of the given table

static Future<void> fetchAllData() async {
try {
dynamic results = await connection.query("SELECT * FROM ${Constants.usersTable}");
if (results.isEmpty) {
print("No Record Found");
} else {
for (final row in results) {
var a = row[0];
var b = row[1];
print("A = " + a);
print("B = " + b);
}
}
} on PostgreSQLException catch (e) {
print(e.message);
}
}

Queries for closing the DB connection

static Future<void> requestForDBConnectionStop() async {
try {
await connection
.close()
.then((value) => debugPrint("Connection successfully close"));
} on PostgreSQLException catch (e) {
print(e.message);
}
}

Conclusion:

In the article, I have explained the implementation of PostgreSQL In Flutter; you can modify this code according to your choice. This was a small introduction to the implementation of PostgreSQL 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 to Implement PostgreSQL In Flutter in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on PostgreSQL with Flutter in your Flutter applications. So please try it.

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


You can check out Implement PostgreSQL In Flutter on GitHub. We hope you enjoyed this tutorial

GitHub – rahul-t-aeologic/postgres_with_flutter_demo
Contribute to rahul-t-aeologic/postgres_with_flutter_demo development by creating an account on GitHub.github.com


From Our Parent Company Aeologic

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

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

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

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

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


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.


2026 Ultimate Guide: Real-time Socket Communication in Flutter…

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.

Related: How to Integrate Real-Time AI Chatbots in Flutter Using OpenAI, Gemini & Local Models