Google search engine
Home Blog Page 71

AWS Amplify Analytics with Flutter

0

This blog will explore the AWS Amplify Analytics with Flutter. We will also implement a demo program, and learn how to use AWS Amplify Analytics 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 Content

AWS Amplify Libraries

Amplify Analytics

Uses

Integration With Flutter

Installation

Pre-requisite

Code Implementaion

Final Output

Conclusion

GitHub Link

Reference


AWS Amplify Libraries:-

The Amplify open-source client libraries are designed to simplify and streamline the interaction between mobile and web developers and their AWS backend resources. These libraries offer easy-to-use interfaces for various categories of AWS cloud operations, making it convenient for developers to integrate and interact with their backend services.

With the Amplify libraries, developers can focus on building their applications without worrying about the intricacies of managing AWS services directly. The libraries provide a set of pre-built functions and APIs that abstract away the complexity of interacting with AWS services, allowing developers to perform common tasks and operations with just a few lines of code.

Whether developers are working with new backends created using the Amplify Command Line Interface (CLI) or existing backend resources, the Amplify libraries can be utilized to simplify the integration and communication process. This flexibility enables developers to seamlessly work with their preferred backend setup and leverage the power of AWS services without needing deep knowledge of AWS-specific APIs or configurations.

Amplify Analytics:-

The Analytics category in Amplify provides functionality to collect analytics data for your application. It offers built-in integration with Amazon Pinpoint and Amazon Kinesis (currently available only in the Amplify JavaScript library).

By using the Analytics category, you can track and gather valuable insights about user behavior, engagement, and usage patterns within your app. This data can be used to make informed decisions, improve user experiences, and optimize your app’s performance.

The Analytics category relies on Amazon Cognito Identity pools to identify and differentiate users within your app. It allows you to collect data from both authenticated and unauthenticated users, providing a comprehensive view of user interactions.

Uses:-

— Capturing User Events One of the primary benefits of Amplify Analytics is its ability to capture user events. You can track various events in your app, such as screen views, button clicks, form submissions, and more. By logging these events, you can understand how users navigate through your app and identify areas for improvement.

The Amplify Flutter library provides a AnalyticsRecordEvent API that allows you to log custom events with associated attributes and metrics. For example, you can log an event when a user adds a product to their cart and include attributes such as the product ID, name, and price. These events and associated data are then sent to the Amplify Analytics service for analysis.

— User Session Tracking Amplify Analytics also enables you to track user sessions, which provide valuable insights into how users engage with your app over time. A session represents a period of user activity within your app, typically starting when the app is launched and ending when the app is closed or put into the background.

The Amplify Flutter library automatically tracks user sessions and records session-related data, such as the session start time, duration, and the number of events logged during the session. This information can help you understand user engagement patterns and identify trends or anomalies.

— User Demographics and Segmentation Understanding your app’s user demographics is crucial for tailoring your app’s features and content to your target audience. Amplify Analytics allows you to collect user demographic data, including attributes such as age, gender, location, and language preferences.

By leveraging this demographic data, you can segment your user base and gain insights into how different user groups interact with your app. For example, you can analyze the behavior of users from different regions or age groups to identify specific usage patterns and preferences. This information can guide your decision-making process when designing new features or optimizing existing ones.

— Data Visualization and Analysis AWS Amplify Analytics provides a comprehensive set of tools for visualizing and analyzing user behavior data. The Amplify Console, a web-based management console, allows you to view real-time metrics and create custom dashboards to monitor your app’s key performance indicators (KPIs).

Integration with Flutter:-

Integrating AWS Amplify Analytics into a Flutter app is a straightforward process. First, you need to set up an Amplify project and configure the Analytics category. This involves creating an Amplify project, adding the Analytics category, and configuring the necessary settings such as the Amazon Pinpoint project.

Once the setup is complete, you can use the Amplify Flutter library to start tracking user events and sending them to the Amplify Analytics service. The library provides a set of APIs that allow you to log custom events, record user sessions, and track user demographics. These APIs are designed to be simple and intuitive, making it easy to instrument your app with analytics capabilities.

Installation:-

There are a few packages that need to be imported into our Flutter project to implement Amplify Analytics.

Add packages to the dependency block, like below,

dependencies:
amplify_flutter: ^0.6.0
amplify_auth_cognito: ^0.6.0
amplify_authenticator: ^0.2.0
amplify_storage_s3: ^0.6.0
amplify_api: ^0.6.0

Pre-requisites:-

Before starting make sure of these steps.

  • Install the latest version of Flutter.
  • Create an account on AWS Amplify if you do not have one.
  • Create a user and generated a security key.

We need to setup amplify in our project, to install run the following command in your terminal

npm install -g @aws-amplify/cli

Afterward, initialize amplify in the flutter project. To do so follow the below steps:

— To ensure proper installation of the Amplify CLI version, execute the following command:

amplify --version

— To connect to the AWS cloud and initialize Amplify, use the following command:

amplify init

Once you’re done, you will find a file automatically created for configurations of amplify, named ‘amplifyconfiguration. dart’. This will help connect your project to AWS Amplify.

— To initialize Amplify, you need to call the Amplify.configure() method. Here’s an example of how to initialize Amplify:

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

class MyApp extends StatefulWidget {
...

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

void _configureAmplify() async {
try {
await Amplify.addPlugin(AmplifyAuthCognito());
await Amplify.addPlugin(AmplifyStorageS3());
await Amplify.addPlugin(
AmplifyAPI(modelProvider: ModelProvider.instance));
await Amplify.configure(amplifyconfig);
} on Exception catch (e) {
print('Error configuring Amplify: $e');
}
}
}

...
}

In the above, the _configureAmplify() function is called to initialize Amplify. The method uses the Amplify.addPlugin() method to add the required plugins (such as AmplifyAuthCognito and AmplifyDataStore) to Amplify. It then calls Amplify.configure() with the amplifyconfig object to provide the necessary configuration.

Code Implementation:-

  • main.dart:-
void main() {
runApp(const MyApp());
}

class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);

@override
State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Authenticator(
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
useMaterial3: true),
home: const MyHomePage(title: 'Flutter Amplify Quickstart'),
builder: Authenticator.builder(),
));
}

@override
void initState() {
super.initState();
_configureAmplify();
}
void _configureAmplify() async {
try {
await Amplify.addPlugin(AmplifyAuthCognito());
await Amplify.addPlugin(AmplifyStorageS3());
await Amplify.addPlugin(
AmplifyAPI(modelProvider: ModelProvider.instance));
await Amplify.configure(amplifyconfig);
} on Exception catch (e) {
print('Error configuring Amplify: $e');
}
}
}

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

final String title;

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

class _MyHomePageState extends State<MyHomePage> {
final _nameController = TextEditingController();
final _locationController = TextEditingController();
final _languageController = TextEditingController();
UserProfile? _userProfile;

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

void _getUserProfile() async {
final currentUser = await Amplify.Auth.getCurrentUser();
GraphQLRequest<PaginatedResult<UserProfile>> request = GraphQLRequest(
document:
'''query MyQuery { userProfilesByUserId(userId: "${currentUser.userId}") {
items {
name
location
language
id
owner
createdAt
updatedAt
userId
}
}}''',
modelType: const PaginatedModelType(UserProfile.classType),
decodePath: "userProfilesByUserId");
final response = await Amplify.API.query(request: request).response;

if (response.data!.items.isNotEmpty) {
_userProfile = response.data?.items[0];

setState(() {
_nameController.text = _userProfile?.name ?? "";
_locationController.text = _userProfile?.location ?? "";
_languageController.text = _userProfile?.language ?? "";
});
}
}

@override
Widget build(BuildContext context) {
return Stack(
children: [
Image.asset(
"assets/background.jpg",
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
),
Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
backgroundColor: Colors.transparent,
foregroundColor: Colors.white,
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Card(
margin: const EdgeInsets.symmetric(horizontal: 30),
child: Padding(
padding: const EdgeInsets.all(30),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 20),
child: Text(
'User Profile',
style: Theme.of(context).textTheme.titleLarge,
)),
const ProfilePicture(),
TextField(
decoration: const InputDecoration(labelText: "Name"),
controller: _nameController,
),
TextField(
decoration:
const InputDecoration(labelText: "Location"),
controller: _locationController,
),
TextField(
decoration: const InputDecoration(
labelText: "Favourite Language"),
controller: _languageController,
)
],
),
))),
floatingActionButton: FloatingActionButton(
onPressed: _updateUserDetails,
tooltip: 'Save Details',
child: const Icon(Icons.save),
),
)
],
);
}

Future<void> _updateUserDetails() async {
final currentUser = await Amplify.Auth.getCurrentUser();

final updatedUserProfile = _userProfile?.copyWith(
name: _nameController.text,
location: _locationController.text,
language: _languageController.text) ??
UserProfile(
userId: currentUser.userId,
name: _nameController.text,
location: _locationController.text,
language: _languageController.text);

final request = _userProfile == null
? ModelMutations.create(updatedUserProfile)
: ModelMutations.update(updatedUserProfile);
final response = await Amplify.API.mutate(request: request).response;

final createdProfile = response.data;
if (createdProfile == null) {
safePrint('errors: ${response.errors}');
}
}
}

You’ll find the entire code file in the GitHub Link section below.

Final Output:-

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

Conclusion:-

In this article, we have delved into the implementation of AWS Amplify Analytics in our Flutter application. By incorporating this powerful tool, we can effortlessly track user events, enabling us to gain valuable insights into user behavior and app performance.

Now that you have gained an understanding of the process, feel free to customize and experiment with your unique approach. Unleash your creativity and explore the vast potential of AWS Amplify Analytics in optimizing your app’s success.

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

🖥️ Github Project —

GitHub – flutter-devs/aws_analytics_demo: AWS Amplify Analytics
AWS Amplify Analytics. Contribute to flutter-devs/aws_analytics_demo development by creating an account on GitHub.github.com


Reference:-

📃 AWS Amplify Docs — https://docs.amplify.aws/lib/analytics/getting-started/q/platform/js


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.


Integrate UPI Payment Gateway Using SDK In Flutter

0

This blog will explore the Integrate UPI Payment Gateway Using SDK In Flutter. We will also implement a demo program, and learn how to integrate UPI payment gateway using SDK 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

Understanding UPI and its significance

Choosing the Right UPI SDK

Key features of UPI Payment Gateway

Setting up your flutter project

Gradle setup

Installing the UPI SDK

Initialising UPI payment

EasyUpiPaymentModel

Parameters Of EasyUpiPaymentModel

TransactionDetailModel

Parameters Of TransactionDetailModel

Final Output

Conclusion

Github Link


Introduction:-

In today’s fast-paced digital world, providing seamless and secure payment options within a mobile app is crucial for enhancing user experience and driving business growth. The Unified Payments Interface (UPI) has revolutionized digital payments in India, offering a simple and efficient way for users to transfer funds and make payments instantly. By integrating a UPI payment gateway into your Flutter app, you can enable your users to make hassle-free transactions, whether for purchasing products, paying bills, or transferring money.

This comprehensive article will walk you through the process of integrating a UPI payment gateway into your Flutter app. Whether you’re a seasoned developer or just getting started with Flutter, this article will provide you with step-by-step instructions and best practices to implement UPI payments successfully. By the end of this article, you’ll have a deep understanding of how to create a seamless payment experience for your users while ensuring the highest standards of security.

Understanding UPI and its Significance:

Unified Payment Interface (UPI) is a groundbreaking payment system that allows users to link multiple bank accounts to a single mobile application. This enables seamless fund transfers and transactions between individuals and businesses, eliminating the need for traditional banking methods.

UPI operates 24/7, ensuring real-time transfers, and has gained immense popularity due to its simplicity and security. Integrating UPI into your Flutter app empowers users to make hassle-free payments, boosting customer satisfaction and engagement. This section will provide a comprehensive overview of UPI, its functioning, and why it’s a game-changer for digital payments.

Choosing the Right UPI SDK:

Selecting a suitable UPI Software Development Kit (SDK) is vital. Compare SDK options such as Paytm, Razorpay, and BharatPe, evaluating factors like integration complexity, documentation quality, community support, and compatibility with your Flutter project.

Key features of UPI Payment Gateway:

  • Seamless Transactions: Users can make payments seamlessly within your Flutter app, reducing friction and enhancing the overall user experience.
  • Wide Payment Acceptance: UPI supports a wide range of use cases, including person-to-person transfers, bill payments, online shopping, and more, making your app versatile and accommodating various transaction types.
  • Real-Time Processing: UPI payments are processed in real-time, allowing users to receive instant confirmation and updates about the status of their transactions.
  • Enhanced Security: By leveraging a reputable UPI SDK, you ensure that sensitive financial data is encrypted and protected, offering a secure payment environment for users.
  • User-Friendly Interface: Your app can provide a user-friendly payment interface where users can easily input payment details, review transactions, and initiate payments without hassle.
  • Payment Status Updates: Users receive immediate updates on the success or failure of their transactions, ensuring transparency and reducing uncertainty.
  • Convenient Payment Methods: UPI allows users to link multiple bank accounts to a single app, giving them the flexibility to choose their preferred payment source.
  • QR Code Support: UPI supports QR code payments, enabling users to scan QR codes to initiate payments quickly and effortlessly.
  • Cross-Bank Compatibility: UPI enables transactions between different banks, making it easy for users with accounts across various banks to transact seamlessly.
  • Error Handling: The UPI SDK can provide robust error handling mechanisms, helping to manage potential issues during the payment process and providing users with clear error messages.

Setting Up Your Flutter Project:

Initiate your Flutter project by creating a new app or modifying an existing one. Ensure that Flutter and Dart are installed, and set up your project with the required dependencies in the pubspec.yaml file.

Gradle Setup:

  • In build.gradle of the app module, include this below dependency to import the EasyUpiPayment library in the app.
dependencies {
implementation "dev.shreyaspatil.EasyUpiPayment:EasyUpiPayment:3.0.3"
}
  • Furthermore, within the debugConfig, update the minSdkVersion to 19.
defaultConfig {
minSdkVersion 19
}

Installing the UPI SDK:

Integrate your chosen UPI SDK into your project by adding the SDK dependency to the pubspec.yaml file.

dependencies:
flutter:
sdk: flutter

easy_upi_payment: <latest version>
  • Run the flutter pub get command to install the dependency, making the SDK’s functionalities available in your Flutter app.

Initialise UPI payment:

The startPayment() a method is likely designed to initiate a UPI payment transaction within a Flutter app.

ref.read(mainStateProvider.notifier).startPayment(
EasyUpiPaymentModel(
payeeVpa: payeeVpaController.text,
payeeName: payeeNameController.text,
amount: double.parse(amountController.text),
description: descriptionController.text,
),
);
  • We pass an object of EasyUpiPaymentModel as a parameter of the startPayment() method.

EasyUpiPaymentModel:

class EasyUpiPaymentModel {

final String payeeVpa;
final String payeeName;
final String? payeeMerchantCode;
final String? transactionId;
final String? transactionRefId;
final String? description;
final double amount;

const EasyUpiPaymentModel({
required this.payeeVpa,
required this.payeeName,
required this.amount,
required this.description,
this.payeeMerchantCode,
this.transactionId,
this.transactionRefId,
});
}

Parameters Of EasyUpiPaymentModel:

  1. payeeVpa (Virtual Payment Address): The recipient’s UPI identifier, often in the format username@upi. This is similar to an email address but used for payments.
  2. payeeName : It takes the name of the payee/recipient like the User Name.
  3. amount: The amount of money to be transferred in the transaction.
  4. transactionRefId (Optional): A reference string or ID associated with the transaction for tracking and reconciliation purposes.
  5. transactionId (Optional): This field is used in Merchant Payments generated by PSPs. If provided null then it uses [DateTime.now().microsecondsSinceEpoch]
  6. payeeMerchantCode (Optional): A code that identifies the merchant initiating the payment, often used for business-specific purposes.
  7. description (Optional): A short description or note about the payment.

We get an object of TransactionDetailModel as the return from the startPayment() method.

Future<TransactionDetailModel?> startPayment(
EasyUpiPaymentModel easyUpiPaymentModel,
) {
throw UnimplementedError('startPayment() has not been implemented.');
}

TransactionDetailModel:

class TransactionDetailModel {
final String? transactionId;
final String? responseCode;
final String? approvalRefNo;
final String? transactionRefId;
final String? amount;

const TransactionDetailModel({
required this.transactionId,
required this.responseCode,
required this.approvalRefNo,
required this.transactionRefId,
required this.amount,
});
}

Parameters Of TransactionDetailModel:

  1. transactionId: A unique identifier assigned to the payment transaction.
  2. responseCode : A numerical code that represents the outcome of the payment. Different codes usually correspond to different types of results, such as success, failure, or other specific scenarios.
  3. approvalRefNo: A reference number provided by the payment gateway or bank to identify the approval of the transaction.
  4. transactionRefId : A reference ID assigned to the transaction, which might be useful for tracking and reconciliation purposes.
  5. amount : The amount of money involved in the transaction.

We have the flexibility to adapt and utilize these fields as per our specific -requirements within the user interface. Hence, the UPI payment service has been seamlessly integrated into our Android app, ensuring a smooth and efficient user experience 😃.

You’ll find the entire code in the GitHub Link mentioned below.

Final Output:

As we run the application, this is what we get as our final output.


Conclusion:

In this article, we’ve explored the process of seamlessly incorporating UPI payment services into our Flutter app. Hope you found the article useful to you😃.

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

GitHub – flutter-devs/upi_pay_app
Contribute to flutter-devs/upi_pay_app 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.


3D Models In Flutter

0

3D models are those model which has 3 measurements length, width, and depth. These models give an incredible user experience when utilized for different purposes. What’s more, adding such a sort of perception to your application will be extremely useful for the user, helping your application develop and attract an enormous crowd.

In this article, we will 3D Models In Flutter. We will implement a 3d model demo program and show 3D models in the glTF and GLB formats using the model_viewer_plus package in your Flutter applications.

  • For Model Viewer Plus

model_viewer_plus | Flutter package
A Flutter widget for rendering interactive 3D models in the glTF and GLB formatspub. 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

Features

Parameters

Implementation

Code Implement

Code File

Conclusion



Introduction:

A Flutter widget for delivering interactive 3D models in the glTF and GLB designs. The widget inserts Google’s <model-viewer> web part in a WebView. The 3D model shows a 3D picture, and the user ought to turn toward any path for the watcher.

Demo Module :

This demo video shows how to create a 3d model in a flutter. It shows how the 3d model will work using the model_viewer_plus package in your Flutter applications. It shows 3D models in the glTF and GLB format and rotates 360° degrees by mouse, hand touch, and auto-rotate. It will be shown on your device.

Features:

There are features of the model viewer plus:
  • > It renders glTF and GLB models. (Also, USDZ models on iOS 12+.)
  • > It Supports animated models with a configurable auto-play setting.
  • > It optionally supports launching the model into an AR viewer.
  • > It optionally auto-rotates the model with a configurable delay.
  • > It supports a configurable background color for the widget.

Parameters:

There are some parameters of the model viewer are:
  • > src: This parameter is used for the URL or path to the 3D model. This parameter is required. Only glTF/GLB models are supported.
  • > alt: This parameter is utilized to design the model with custom content that will portray the model to watchers who utilize a screen reader or, in any case, rely upon an extra semantic setting to comprehend what they are seeing.
  • > autoRotateDelay: This parameter sets the deferral before auto-revolution starts. The configuration of the worth is a number in milliseconds. The default is 3000.
  • > iosSrc: This parameter is used to the URL to a USDZ model, which will be used on supported iOS 12+ devices via AR Quick Look.
  • > arScale: This parameter is utilized to control the scaling conduct in AR mode in Scene Viewer. Set to “fixed” to incapacitate the model’s scaling, which sets it to be at 100% scale consistently. Defaults to “auto,” which permits the model to be resized.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

model_viewer: ^0.8.1

Step 2: Add the assets

assets:
- assets/

Step 3: Import

import 'package:model_viewer_plus/model_viewer_plus.dart';

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

Step 5: AndroidManifest.xml (Android 9+ only)

android/app/src/main/AndroidManifest.xml

To utilize this widget on Android 9+ devices, your application should be allowed to make an HTTP association with http://localhost:XXXXX. Android 9 (API level 28) changed the default forandroid:usesCleartextTrafficfrom true to false.

<application android:name="${applicationName}" 
android:icon="@mipmap/ic_launcher" 
android:label="example"
android:usesCleartextTraffic="true">

Step 6: app/build.gradle (Android only)

Change minSdkVersion to 21.
defaultConfig {    minSdkVersion 21}

Step 4:Info.plist (iOS only)

To enable the widget on iOS, add a boolean property named “io.flutter.embedded_views_preview” to your app’s ios/Runner/Info.plist file with the value “YES”.

<key>io.flutter.embedded_views_preview</key>  <true/>

How to implement code in dart file :

You need to implement it in your code respectively:

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

In the body, we will add ModelViewer(). Inside, we will add a backgroundColor for the model viewer; src means the user adds URL and assets only glTF/GLB models are supported.

ModelViewer(
        backgroundColor: Colors.teal[50]!,
        src: 'assets/table_soccer.glb',
        alt: "A 3D model of an table soccer",
        autoPlay: true,
        autoRotate: true,
        cameraControls: true,
      ),

We will add alt means configures the model with custom text that will describe the model to viewers who use a screen reader; autoplay means if this is true and a model has animations, an animation will automatically begin to play when this attribute is set. The default is false. We will add autoRotate means it enables the auto-rotation of the model. We will add cameraControls which enables controls via mouse/touch when in flat view.

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:model_viewer_plus/model_viewer_plus.dart';

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

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

class _DemoViewState extends State<DemoView> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Flutter 3D Model Viewer Demo"),
        automaticallyImplyLeading: false,
        backgroundColor: Colors.black,
        centerTitle: true,
      ),
      body: ModelViewer(
        backgroundColor: Colors.teal[50]!,
        src: 'assets/table_soccer.glb',
        alt: "A 3D model of an table soccer",
        autoPlay: true,
        autoRotate: true,
        cameraControls: true,
      ),
    );
  }
}

Conclusion:

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

I hope this blog will provide you with sufficient information to try up the 3D Model in your flutter projectsWe will show you what the Introduction is?. Some model viewer plus features, and parameters, make a demo program for working 3D Models and show 3D models in the glTF and GLB format and rotate 360° degrees by mouse, hand touch, and auto-rotate using the  model_viewer_plus package 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.


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! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

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.


Supabase Database with Flutter: Building Powerful Apps with Real-Time Functionality

0

This blog will explore the Supabase Database with Flutter: Building Powerful Apps with Real-Time Functionality. We will also implement a demo program, and learn how to integrate Supabase 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 — Flutter

What is Supabase?

Features

Getting started with Supabase

Integration of Supabase into Flutter

Code Implementation

Final Output

Conclusion

Github Link

Reference


Introduction:-

Flutter has emerged as a popular choice for building cross-platform mobile applications due to its ease of use and impressive performance. When it comes to integrating a robust backend database into your Flutter app, Supabase offers an excellent solution. In this blog, we’ll explore Supabase and how you can leverage its features to power your Flutter app with a powerful and scalable database. Let’s dive in!

What is Supabase?

In today’s fast-paced world, building powerful and responsive applications is essential to meet the demands of users. And when it comes to developing data-driven applications with real-time functionality, having a robust and scalable backend is crucial. Enter Supabase, an open-source Backend-as-a-Service (BaaS) solution that combines the best of Firebase and traditional databases. It is built on top of PostgreSQL and extends its capabilities with additional features like real-time and Authentication. With Supabase, you get a scalable, secure, and real-time database that can seamlessly integrate with your Flutter app.

In this blog post, we will explore the integration of Supabase with Flutter, allowing you to leverage its real-time database and authentication features to build dynamic and interactive apps. We will delve into the key concepts of Supabase and demonstrate how it empowers developers to create applications that scale effortlessly while maintaining data integrity and security.

Whether you’re a seasoned Flutter developer or just starting your journey, this guide will provide you with a comprehensive understanding of Supabase and its integration with Flutter. By the end, you’ll be equipped with the knowledge to develop powerful, real-time applications backed by a reliable and scalable database solution.

Features:-

  • Managing Data with Supabase

Supabase simplifies data management in your Flutter app. You can use the SupabaseClient class to perform queries, inserts, updates, and deletions. Additionally, you can leverage the real-time functionality to subscribe to changes in the database, ensuring that your app’s data remains up-to-date in real time.

  • Securing Your Flutter App with Supabase Authentication

User authentication is crucial for most applications. Supabase offers built-in authentication features, allowing you to authenticate users through various methods like email/password, social logins (Google, Facebook, etc.), and more. We’ll guide you through implementing secure user authentication in your Flutter app using Supabase.

  • Optimizing Performance with Supabase Indexes

Indexes play a vital role in optimizing database performance. Supabase provides the ability to create indexes on frequently queried columns, significantly improving query response times. We’ll explore how to identify the right columns to index and implement them in your Supabase database.

Getting Started with Supabase:

To begin using Supabase in your Flutter app, you need to set up a Supabase project. This involves signing up for an account in the dashboard and creating a new project here.

Once your project is set up, you will receive a URL and API key, essential for accessing the Supabase database.

To get the URL and API key, follow the below guidelines:

  1. After successfully signing in and creating your project, go to the Home option.

2. Navigate to the Project API section below, where you’ll discover the URL and API key of your Supabase project.

Integration of Supabase into Flutter:

With your Supabase project ready, it’s time to integrate it into your Flutter app. You can do this using the Supabase Dart package, which provides a set of APIs to interact with the Supabase backend. Through these APIs, you can perform CRUD operations, manage user authentication, and subscribe to real-time data updates. Follow the below steps to do so:

Import the latest version of the supabase_flutter package in pubspec.yaml file of your Flutter project.

dependencies:
supabase_flutter: ^1.10.9

— Initialise Supabase in the Flutter project by providing the Supabase project’s URL and API key to establish the connection.

Code snippet:

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();

await Supabase.initialize(
url: 'https://***.supabase.co',
anonKey: '***'
);

final supabase = Supabase.instance.client;
runApp(ProviderScope(child: App(supabase: supabase)));
}

Now, armed with the powerful features of Supabase, we are all set to dive into the code implementation.

Code implementation:-

  • main. dart
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();

await Supabase.initialize(
url: '<Supabase project URL>',
anonKey:
'eyJhbGc...',
);

await AppPreference().initialAppPreference();

final supabase = Supabase.instance.client;
runApp(ProviderScope(child: App(supabase: supabase)));
}

class App extends StatelessWidget {
const App({Key? key, required this.supabase}) : super(key: key);
final SupabaseClient supabase;

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/', routes: <String, WidgetBuilder>{
'/': (_) => SplashPage(supabase: supabase),
'/login': (_) => LoginPage(supabase: supabase),
'/register': (_) => RegisterUser(supabase: supabase),
'/home': (_) => HomeScreen(),
// home: Home(supabase: supabase),
});
}
}

Authentication:-
  • login. dart
class LoginPage extends StatefulWidget {
const LoginPage({super.key, this.supabase});
final SupabaseClient? supabase;

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

class LoginPageState extends State<LoginPage> {

...

Future<void> _signIn() async {
try {
debugPrint("EMAILLL: ${_emailController.text}, PASSS: ${_passwordController.text}");
await widget.supabase?.auth.signInWithPassword(email: _emailController.text, password: _passwordController.text);
if (mounted) {
_emailController.clear();
_passwordController.clear();

_redirecting = true;
Navigator.of(context).pushReplacementNamed('/home');
}
} on AuthException catch (error) {
context.showErrorSnackBar(message: error.message);
} catch (error) {
context.showErrorSnackBar(message: 'Unexpected error occurred');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Center(child: Text('Login')), backgroundColor: Colors.teal),
body: SingleChildScrollView(

...

Padding(
padding: const EdgeInsets.only(top: 25.0),
child: Container(
height: 50,
width: 250,
decoration: BoxDecoration(color: Colors.teal, borderRadius: BorderRadius.circular(20)),
child: TextButton(
// style: ButtonStyle(backgroundColor: MaterialStateColor.resolveWith((states) => Colors.teal), ),
onPressed: () async {
if (_formKey.currentState!.validate()) {
_signIn();
}
},
child: const Text(
'Login',
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
),
const SizedBox(
height: 130,
),
TextButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (_) =>
// RegisterUser(supabase: widget.supabase ?? Supabase.instance.client)
SignUpPage(supabase: widget.supabase ?? Supabase.instance.client)
));
},
child: const Text('Don\'t have an account?', style: TextStyle(color: Colors.teal),)),
const SizedBox(
height: 30,
),

...
),
);
}
}

  • signup. dart
class SignUpPage extends StatefulWidget {
const SignUpPage({super.key, required this.supabase});

final SupabaseClient supabase;

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

class SignUpPageState extends State<SignUpPage> {

...

Future<void> _signUp() async {
try {
AuthResponse response = await widget.supabase.auth.signUp(
password: _passwordController.text, email: _emailController.text);
if (mounted) {
_redirecting = true;
print("Userrr -- ${response.user}");
_saveId(response.user);
Navigator.of(context).pushReplacementNamed("/register").then(
(value) => context.showSnackBar(message: "Verify your email!"));
setState(() {});
}
} on AuthException catch (error) {
context.showErrorSnackBar(message: error.message);
} catch (error) {
context.showErrorSnackBar(message: 'Unexpected error occurred');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sign Up'),
backgroundColor: Colors.teal,
),
body: SingleChildScrollView(
child:
...

Container(
height: 50,
width: 250,
decoration: BoxDecoration(
color: Colors.teal,
borderRadius: BorderRadius.circular(20)),
child: TextButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
if (_passwordController.text ==
_confPasswordController.text) {
_signUp();
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
"Passwords didn't match! Try again.")));
}
}
},
child: const Text(
'Sign Up',
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
const SizedBox(
height: 130,
),

...
}
}

You’ll get the entire code below the GitHub Link.

Final Output:-

Now, for a successful login, the email you used during sign-up needs to be verified. After verifying the email, I returned to the app.

Conclusion:-

In this blog, we comprehensively understood the Supabase database and its powerful functionalities. Now, it’s time to apply this knowledge to your projects and delve deeper into the possibilities it offers. Happy exploring!

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

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

Reference:-

📃 AWS Amplify Docs —

Supabase Docs
Supabase is an open-source Firebase alternative providing all the backend features you need to build a product.supabase.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.


Flutter 3.19 — What’s New In Flutter

0

In this blog, we will learn about Flutter 3.19. We will also implement a demo and how to use them in your Flutter applications. So let’s get started.

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 flutter 3.19

What’s new we got?

Conclusion

Reference Url


Introducing Flutter 3.19:

Today marks the arrival of Flutter 3.19, a milestone release packed with exciting new features and enhancements. Among the highlights is the introducing of a new Dart SDK for Gemini, empowering developers with enhanced performance and capabilities. Additionally, developers now have access to a versatile widget designed to offer precise control over widget animations, alongside rendering improvements with updates to Impeller.

Flutter 3.19 doesn’t stop there; it also introduces essential tooling for implementing deep links, streamlining the development process. Moreover, this release extends support to Windows Arm64, broadening the range of platforms developers can target with their Flutter applications.

The Flutter community’s dedication is evident in this release, with an impressive 1429 pull requests merged, contributed by 168 community members. Notably, 43 individuals made their inaugural contributions to the Flutter codebase, underscoring the vibrancy and inclusivity of the Flutter community.

Keep reading to discover the latest additions and improvements that define this remarkable release!

What’s new we got?

AI Integration: — 

Gemini Google AI Dart SDK (beta) — Beta release of Google AI Dart SDK integrates generative AI into Dart/Flutter apps via Gemini models. Explore google_generative_ai package on pub.dev for quickstarts & tutorials.

Framework: —

Scrolling improvements — In the latest Flutter update, scrolling behavior has been enhanced for smoother navigation. MultiTouchDragStrategy.latestPointernow offers consistent scrolling regardless of the number of fingers used. Bugs inSingleChildScrollViewandReorderableList have been fixed, addressing crashes and unexpected behavior. Two-dimensional scrolling has been refined, ensuring interruptions during scroll actions. Additionally, TableView in the two_dimensional_scrollables package has received updates, including enhanced features like merged cells and compatibility with the 2D foundation improvements.

=AnimationStyle — Flutter introduces the AnimationStylewidget, empowering developers to customize animation behavior in MaterialApp, ExpansionTile, andPopupMenuButton, including curve and duration overrides.

SegmentedButton.styleFrom — Introduction of styleFrom method for SegmentedButton, facilitating easy creation of ButtonStyle for shared usage or theme configuration.

Adaptive Switch —The adaptive component seamlessly blends into macOS/iOS or adopts Material Design elsewhere. Consistent API across platforms, independent of Cupertino library. See adaptive switch PR& live example on Switch.adaptive constructor API page.

Increased access to text widget state — Support for MaterialStatesControllerinTextFieldandTextFormField facilitates listening to MaterialStatechanges.

Engine: — 

Impeller progress —Flutter 3.16’s Impeller on Vulkan for Android covers 77% devices, now with OpenGL feature parity including MSAA. Developers urged to upgrade, report issues for refinement. Detailed device and Android version feedback crucial. Vulkan offers enhanced debugging but with added runtime overhead. Performance focus post-fidelity, with Vulkan subpasses for blend modes, CPU utilization reduction via Stencil-then-cover, and Gaussian blurring improvements for iOS. Read more.

API improvements: — 

Glyph Information —New methods, getClosestGlyphInfoForOffset and getGlyphInfoAt, are added to dart:ui’s Paragraphobject, introducing the GlyphInfotype. Refer to the documentation for details on GlyphInfo.

GPU tracing — Flutter engine now provides GPU frame timing on Impeller for iOS/macOS/Simulator and Vulkan-enabled Android devices in debug/profile builds, accessible in DevTools under “GPUTracer”. Impeller’s GPU tracing requires a flag in AndroidManifest.xml due to potential misreporting by non-Vulkan Android devices regarding GPU timing support.

<meta-data
android:name="io.flutter.embedding.android.EnableOpenGLGPUTracing"
android:value="true" />

Performance optimizations: — 

Specialization constants — Adding support for specialization constants to Impeller reduced the Flutter engine’s uncompressed binary size by nearly 350KB.

and others.

Android: — 

Deeplinking web validator — Developers find deep linking challenging and error-prone. To address this, 3.19 has released an early version of the Flutter deep link validator. It currently supports web checks on Android, validating assetlinks.jsonsetup. Simply import your Flutter project into DevTools to verify your configuration. Future updates will include web check on iOS and app check on both platforms, aiming to simplify deep linking implementation. Read more.

Support for Share. invoke — In this release, the default Share button on Android text fields and views has been added to ensure all default context menu buttons are available on each platform.

Native assets feature — Flutter now enables interoperability with functions from other languages via FFI calls through Native assets on Android, advancing support for Native assets.

Texture Layer Hybrid Composition (TLHC) mode —Flutter 3.19 improves TLHC mode for Google Maps and text input magnifier, enhancing app performance.

Custom system-wide text selection toolbar buttons — Flutter’s TextField selection menu integrates custom text selection menu items from Android apps, enhancing user experience.

iOS: — 

Flutter iOS native fonts — Flutter text now appears more compact and native on iOS, adhering to Apple design guidelines. Smaller fonts are now spaced out for readability, while larger fonts are compact to save space. Previously, Flutter incorrectly used the spaced-out font for all text sizes. For example, check here.

DevTools: — 

DevTools updates — New DevTools release highlights:

  • Android deeplinks validation feature added.
  • Enhance Tracing menu now tracks platform channel activity, which is beneficial for plugin-based apps.
  • Performance and CPU profiler screens are accessible without a connected app, allowing reloading of saved data.
  • The Flutter Sidebar in VS Code enables new platforms and offers the option to open DevTools in the external browser window.

Desktop: — 

Windows Arm64 support — Flutter on Windows introduces initial Arm64 support, promising enhanced performance for apps on Windows Arm64 devices. Development progress is tracked on GitHub issue #62597, offering Flutter developers broader optimization possibilities.

Conclusion:-

We’ve comprehensively explored nearly all the new features introduced in Flutter 3.19 in this blog. We hope you found it insightful and enjoyable. Take the opportunity to delve into these new features and explore their practical applications.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.

Reference Url:-

What’s new in Flutter 3.19
Revolutionizing App Development with the Gemini API, Impeller Updates, and Windows Arm64 Supportmedium.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.


CI/CD with Bitbucket In Flutter

0

This blog will explore the CI/CD with Bitbucket In Flutter. We perceive how to execute a demo program. We will show you how to use a CI/CD with Bitbucket 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.


Why do we need to use CI/CD as an extra step in our development, and configure DevOps-like things in our development routine?

Life is full of challenges and we handle them very efficiently. There are some situations when we don’t know what to do, which can be avoided only by adopting automation in the system.
Let’s assume you have worked hard with entire focus throughout the week and then finished your work to meet your deadline. Now you want to have a party with your friends and at the party, you get a call that the build you shared with the client is not installed on his device and as you are smart you realize that you forgot to clean the project before making a build.

Will you leave the party and get back to your laptop to check it or you call your subordinates to make a build with full cleaning this was the sole purpose of your party, and you don’t want to disappoint your client. Situations can vary but actual things come out in actual scenarios, not virtual ones.

Then your friend tells you that he has set up the CI/CD in his project on bitbucket or git-like VCS in which the build is tested before every push with full clean passing of all the lint warnings and test cases and he doesn’t need to even share any build as the build gets auto uploaded to the desired place by DevOps engine like Jenkins.

Now you know why CI/CD is important.
There are other benefits also like if you have a large team of developers and some are lazy ones to test their code before committing to the cloud, then your army of test cases and intelligence of CI/CD will handle them for you, you can have party!!!.

What is CI/CD?

You know about it already though we can assume it is a system that continuously tests and deploys the code before and after the situation you want as a set of tools to automate our code integration, testing, and deployment.

Bitbucket, Git, Gitlab all offers it, 
Also, there is Jenkins, CI which does the job very well and uploads your artifacts on the Play Store, app center, app store, and other distribution channels.

How can we do it?

The process seems to be tough as everything new for us looks tough and our mind finds excuses to avoid it.

So don’t think too much and stay with me, you will have a lot of it in the next 5 mins.

Ingredients:

Bitbucket account, a flutter project and that’s it.

Steps:

To be concise I will be doing it fast but let me know if you need any further explanation so I can write a detailed blog on then, Let’s start…

  • > Create a repository on bitbucket and clone your flutter code on it.
  • > Create a .yaml file and open it in edit mode.
  • > Put this code in the file and save it.
image: mobiledevops/flutter-sdk-image:3.10.3
pipelines:
branches:
master:
- step:
script:
- echo "This script runs only on commit to the main branch."
- flutter pub get
- flutter build apk --release
artifacts:
- build/app/outputs/apk/release/*
feature/*:
- step:
script:
- echo "This script runs only on commit to the main branch."
- flutter pub get
- flutter build apk --release
artifacts:
- build/app/outputs/apk/release/*
  • > It will run and build the apk from the code and upload it in artifacts.
  • > You can download it from the artifacts section.

NOTE: Keep the indentation the same as it will create issues in compiling.

Now, the Fast and Furious one is done here, and the crazy and curious ones are welcome to understand the meaning of the steps we have taken.

The 3rd step was all the magic so we will see it in slow motion to have it.

1. We defined a docket image to pull for executing the flutter commands.

2. Next we declare the branch or we can have default if you want all branches to have it.

3. Then steps come and we start writing the script

4. Echo are the messages that we want when a step gets executed.

5. Flutter Clean will clean the project which is recommended before making any apk.

6. Flutter build apk — release will make the apk in a release format that is very efficient and not have any dev dependencies and is compact.

7. Artifact gives the path to find your apk so that it can be uploaded to download later from the server.

8. we can add more steps to it like testing and analyzing but those will be covered in the next blog.

Conclusion:

In today’s life, a lot of things are going automated and so TDD(Test-driven development), CI/CD, and other DevOps tools are replacing manpower to remove shallow works in the systems. So learning these concepts and technologies will surely add some value to your database.

The next blog will be on Jenkins with App Center.
Till then Keep Coding, Deep Coding.

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


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.