Google search engine
Home Blog Page 69

Flutter Quill: Rich Text Editor In Flutter Application

Hello Everyone…!!!!. Today we start with an interesting topic that is used for rich text. Flutter Quill is a rich text editor and also a Quill component for 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 Content

Introduction

Add Dependency

Configuration

Implementation

GitHub Link


Introduction:

FlutterQuill is a rich text editor and a Quill component for Flutter. This library is a WYSIWYG editor built for the modern mobile platform, with web compatibility under development. This dependency is very useful for any editor app. We don’t need any other side for code for any texting editor.


Add Dependency:

To add the dependency first you have to open pubspec. ymal file and then add some dependencies,

dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
flutter_quill: ^6.1.6

We have to add the updated package of flutter_quill. Which is used as a Rich Text Editor in a flutter.


Configuration:

The Quill Toolbar class lets you customize which formatting options are available.

> Font Size:- Within the editor toolbar, a drop-down with font-sizing capabilities is available. This can be enabled or disabled with showFontSize. When enabled, the default font-size values can be modified via optional fontSizeValues. FontSizeValues accepts a Map<String, String> consisting of a String title for the font size and a String value for the font size. Example:

fontSizeValues: const {'Small': '7', 'Medium': '20.5', 'Large': '40'},

>Font Family:- If you want to use the font family, you have to add the family to the assets folder and pass in fontfamilyValues.

>Custom Buttons:- You may add custom buttons to the end of the toolbar, via the custom buttons option, which is a List of QuillCustomButton.

QuillCustomButton(
icon:Icons.ac_unit,
onTap: () {
debugPrint('snowflake');
}

>showAlignmentButtons:- In showAlignmentButtons, we have many properties like controller, iconSize, iconTheme, showLeftAlignment, showCenterAlignment, showRightAlignment, showJustifyAlignment, afterButtonPressed.

>Translation:- The package offers translations for the quill toolbar and editor, it will follow the system locale unless you set your own locale with:

QuillToolbar(locale: Locale('fr'), ...)
QuillEditor(locale: Locale('fr'), ...)

Implementation:

In the implementation of Flutter Quill first, we have to create a Flutter project with the name flutter_quill_demo. There are two things in QuillController and Quill-editor. In Quill-controller.

QuillController _controller = QuillController.basic();

here we define the controller as QuillController.basic(). In the Toolbar() we can pass many things like QuillController, toolbarIconAlignment, toolbarIconAlignment, showDividers, showBoldButton, showBoldButton, showUnderLineButton, showJustifyAlignment and many more.

And second is QuillEditor.basic(), in this editor we can type anything.

Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
Container(
margin: EdgeInsets.only(top: 20,left: 10,right: 10,bottom: 20),
width: MediaQuery.of(context).size.width,
height: 80,
decoration: const BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://user-images.githubusercontent.com/10923085/119221946-2de89000-baf2-11eb-8285-68168a78c658.png'),
fit: BoxFit.cover
)
),
),
Padding(padding: const EdgeInsets.only(top: 0),
child:
QuillToolbar.basic(controller: _controller,
fontSizeValues: const {'Small': '7', 'Medium': '20.5', 'Large': '40'},
showAlignmentButtons: false ,
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
decoration: const BoxDecoration(
boxShadow: [BoxShadow(
color: Colors.lightBlueAccent,
offset: Offset(5.0, 5.0) ,
blurRadius: 10.0,
spreadRadius: 2.0
),
BoxShadow(
color: Colors.white,
offset: Offset(0.0, 0.0),
blurRadius: 0.0,
spreadRadius: 0.0
)
]
),
child:
QuillEditor.basic(controller: _controller, readOnly: false),),
)
],
),
),
);

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

In this picture, as you see we can add colors to our text. And by this, we can create an attractive text list.

In this picture, you can see that we can change the font style for particular text. and also for particular paragraphs.

Flutter Quill Demo

GitHub Link:

Find the source code of the Flutter Quill:

GitHub – flutter-devs/flutter_quill_demo
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…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.


Testing In Flutter

0

Testing is an essential part of the app development process, yet it is often overlooked or provided minimal attention. This is a mistake that can have serious consequences, as faulty or buggy apps can lead to user frustration, negative reviews, and even financial losses. In this medium post, we will delve into the importance of testing in app development and various types of testing that can ensure the quality and reliability of your flutter apps.

Testing is an integral phase in the development cycle of an application ensuring that the app is of substantial quality, planned to perfection, and perfectly executed and the phase that commands the most time in the development cycle.

Objective Of Testing

In the app development process, Testing is crucial for ensuring that your app functions properly and as intended. Through testing, you can identify and address any bugs or defects early on, saving time and resources in the long run. Testing also helps to ensure that your app is reliable and maintainable. By writing tests, you can confirm that changes made to the app do not negatively impact its existing functionality, and feel confident in making future changes. Ultimately, testing is a key component of delivering a high-quality app to your users.

  • Automating Process
  • Retaining feature on further scaling
  • Fixing bugs easily
  • Timely feedback on bugs.
  • etter Documentation, Code coverage

Flow Of Test Cases

the flow of test cases

Development Testing In Flutter

Dart language & Flutter framework provides extensive support for the automated testing of an application at different levels.

Flutter provides 3 kinds of tests to test your app:

  • Unit Testing
  • Widget Testing
  • Integration Testing

Unit Testing

Unit tests are used to test individual functions or classes in your app. They are usually isolated from the rest of the app, so they don’t rely on any external state. You can run unit tests from the command line or an IDE by using the flutter test command.

Widget Testing

It is used to test the interaction between different widgets in your app. They allow you to test how widgets behave when they are nested within each other, and how they respond to user input. You can create widget tests by using the flutter test command and running them with the flutter drive command.

Integration Testing

Integration testing includes testing user flows through the app, as well as testing interactions with external APIs or databases. In Flutter, you can use a package like Flutter Driver to create integration tests that run on the command line. These tests can be run on real devices or simulators/emulators.

Test Types Relationship ( Isolation -Time Consumed )

Test Types Relationships

Unit tests are the most isolated and fastest to run, as they test a small, specific unit of code in isolation. They are usually focused on testing individual functions or methods, and do not require the app to be fully built or running.

Widget tests are slightly less isolated, as they test the behavior of a single widget in the context of a running app. They allow you to test the interactions between a widget and its dependencies, as well as the widget’s appearance. Widget tests are typically faster to run than integration tests but may take longer than unit tests.

Integration tests are the least isolated and most time-consuming to run, as they test the interaction between multiple components of the app. They require the app to be fully built and running and can be used to test the app’s behavior end-to-end. Integration tests are useful for verifying that the different parts of the app are working together correctly and as expected.

We are on board with the need for testing and the types of it. Herewith are some key integral parts for writing test cases :

  • : Write the test case inside the main function in the test dart file. All the test cases come under the main function.
  • : Test cases are written under test() function or testWidgets() in case of widget tests.
  • : test function requires a description and test code. description should be as clear for naive understanding as well
  • : Add the test dependency needed at the testcode part.
  • : Different testcases can be grouped based on similarity using the grouping() function.
  • : All the test cases are written using three AAA format

While writing test cases one should be well acquainted with the terminologies used in writing those test cases

Terminologies Used In Test Cases

  • : main() : All the test cases are written inside this function.
  • : group() : All the similar test cases are grouped together on a similarity basis
  • : test() ,testWidgets () : require a description and testcode. description should be apparent clear for even the management person to understand and infer. test code should be written under this function.
  • : Setup, setUpAll: setup common code required for each method. if written outside test cases available for all test cases.
  • : verify, expect: used to verify the test case results in the intended value
  • : tearDown, tearDownAll : used to dispose off things , methods
  • : pumpWidget(): Renders the UI from the given widget.
  • : tap(): Calls the onTap/onPress event of the widget.
  • : pump(): Gets the reflected changes in the Widget. (e.g. setState())
  • : pumpAndSettle(): Repeatedly calls the pump() method with duration until there is no frame to schedule.
  • : WidgetTester: Used to build and interact (re-render) widgets in the test environment.
  • : Finder: Class that allows you to search widgets in a test environment.
  • : Matcher: Verifies Finder locates a widget or multiple widgets in test environment.

Pattern Used In Writing Test Cases ( AAA Structure )

Using the AAA pattern can help you write test cases that are easy to understand and maintain, and can also help you catch errors and bugs more effectively.

  • Arrange: prepare and initialize
  • Act: invoke method testing
  • Assert: validate the result expected

The AAA (Arrange-Act-Assert) pattern is a common approach for writing test cases that can help you structure your tests clearly and logically. The AAA pattern consists of the following steps:

AAA pattern
  1. Arrange: Set up the necessary preconditions for the test. This may involve creating objects, setting up mock data, or performing other necessary setup tasks.
  2. Act: Perform the action that you want to test. This could be calling a function, interacting with a widget, or performing some other action.
  3. Assert: Verify that the action produced the expected result. This may involve checking the return value of a function, checking the state of an object, or verifying that some other condition is true.

Here’s an example of a test case written using the AAA pattern in Flutter:

Simple Test Cases In Flutter

Unit Testing

Unit testing involves testing individual parts of your app, like functions or classes, separately from the rest of the app.

Here is an example of a unit test for a Flutter function that makes an HTTP request using the http package:

unit-testing flutter

This test makes an HTTP GET request to the URL https://flutterdevs.org/get and then verifies that the status code 200 and the response body is as expected.

Note that this test is using the http package to make the HTTP request, but you could also use a mock HTTP library like mockito or dio_mock to test your HTTP client code without actually making real network requests.

Widget Testing

Widget testing involves verifying the behavior of individual widgets within your app. This function allows you to find elements using Finder objects and verify their behavior using Matcher objects.

Here is an example of a widget test for a FileWidget in Flutter:

This test creates an instance of FileWidget with a File object and then uses the WidgetTester to verify that the file name is displayed.

Integration Testing

Integration testing in Flutter involves testing how various parts of your app work together

Here is an example of an integration test for a payment feature in Flutter

This test launches the app, taps the Make Payment button, enters payment information, and taps the Submit Payment button. It then verifies that the payment was successful by checking for the presence of the text Payment Successful.

Code Coverage In Flutter

Code coverage is a measure of how much of your code is being tested by your test suite, understand how thorough your tests are, Identify areas of your code yet to be tested.

Code coverage in Flutter helps ensure that widgets are properly tested and can be measured using tools like coverage. These tools generate reports on tested code, aiding in identifying untested areas and improving the app’s overall quality. Tracking code coverage can also aid in monitoring testing progress and identifying areas for testing focus

Here’s an example of how to implement code coverage in Flutter:

  1. Install the coverage package:
flutter pub add coverage
  1. Run your tests with the coverage command:
flutter test --coverage

This will generate a coverage report in the coverage directory.

  1. To view the coverage report, you can use the coverage:format command:
flutter pub run coverage:format

This will generate an HTML coverage report that you can view in your web browser. The report will show you which lines of code were executed and which were not, so you can see which parts of your code still need to be tested.

For more information on code coverage in Flutter, you can check out the coverage package documentation:

coverage | Dart Package
Coverage provides coverage data collection, manipulation, and formatting for Dart. collect_coverage collects coverage…pub.dev

Herewith is a sample file to help you understand :

code coverage flutter

What’s Next

Tests might depend on classes that fetch data from live web services/databases which is inconvenient as this would fail the test in case of unexpected results from the database / API. To prevent this from happening we deal with such scenarios by Mocking.

This would be discussed in detail in the upcoming blog: Mocking In Flutter

References

Testing Flutter apps
The more features your app has, the harder it is to test manually. Automated tests help ensure that your app performs…flutter.dev

Find widgets
To locate widgets in a test environment, use the classes. While it’s possible to write your Finder classes, it’s…docs. flutter.dev


From Our Parent Company Aeologic

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

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

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

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project 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.

Scrollbar Widget for Flutter Web

0

A scrollbar is an interaction technique in which continuous information/data (text, pictures, or any other type of content) can be scrolled in a predetermined direction (up, down, left, or right). By default scroll direction is vertical.


Table of Contents :

Scrollbar — Introduction

What is a scrollview widget? — Explained

Code Implement

Code File

Conclusion


Scrollbar — Introduction:

A vertical scroll bar gives the user the ability to scroll the content of a window up and down. Similarly, a horizontal scroll bar lets the user scroll the content from left to right.

Flutter has a few widgets that allow users to create a scrollable list of items. If the list is quite long, using a scrollbar would be the best option here which will make the user more comfortable with the interface.

However, The flutter’s ScrollView widgets (e.g. ListView, GridView, CustomScrollView) does not display any scroll bar by default. Fortunately, Flutter makes it very easy to display a scrollbar. We can use a ScrollBar widget and pass to it a widget that contains ScrollView as its child.

What is a ScrollView Widget?

A ScrollView is a widget that creates custom scroll effects using slivers. A container for a Scrollable that responds to drag gestures until a limit is reached, and then scrolling.

Following are a few scroll view examples:-

  • SingleChildScrollView
  • ListView
  • GridView
  • PageView
  • ReorderableListView
  • NotificationListener and etc

> SingleChildScrollView:-

This widget is useful when you have a box that contains a single widget that can be scrolled. For instance, a clock faces a time picker. But there’s something you need to make sure is that it can only be scrolled if the container gets too small in one/both axes (the scroll direction). To know more, click here.

> ListView:-

ListView is the most common scrolling widget. It displays its children’s items one after the other in the scroll direction(vertical by default). In the cross-axis, the children are supposed to fill up the ListView.

> GridView:-

A 2D arrangement of widgets that can be scrolled.

As the name suggests, you’ll see it being used wherever we want to present widgets in a Grid format. We can select the item we desire from the grid list by clicking on them. To know more, click here.

> PageView:-

A list that is scrollable and works page by page. Each child of a page view is forced to be the same size as the viewport.

PageController is what we use to control which page should be visible in the view. It makes users able to control the pixel offset of the content of the PageView. Along with that it also lets you control the offset in terms of pages, which are increments of the viewport size.

> ReorderableListView:-

A list in which a user can interactively reorder its elements/items by drag and drop. The onReorder parameter is what we require which will be called when a child widget is dragged and dropped to a new position. To know more, click here.

> NotificationListener:-

NotificationListener<T extends Notification>

It’s a widget that listens for Notifications bubbling over the tree. Notifications will activate the onNotification callback only when their runtimeType is a subtype of T.

Use the Notification. dispatch method for dispatching notifications.

Code Implement:-

We’ll see a demo code that will implement a Scrollbar in it.

> Constructor:-

Scrollbar({
Key? key,
required Widget child,
ScrollController? controller,
bool? thumbVisibility,
bool? trackVisibility,
double? thickness,
Radius? radius,
ScrollNotificationPredicate? notificationPredicate,
bool? interactive,
ScrollbarOrientation? scrollbarOrientation,
})

Let’s use it in our demo project.

Code:-

Expanded(
child: Scrollbar(
thickness: 20,
thumbVisibility: true,
trackVisibility: true,
interactive: true,
radius: const Radius.circular(15),
child: ListView.builder(...),
),
)

The demo project is for Flutter Web i.e., We’ll be able to see our scrollbar in Chrome(web). It doesn’t make any difference from the emulator view of the project or even it might be more fun.

Here, we will be using ListView as our ScrollView widget. We just need to wrap it with our ScrollBar to get it visible along with the list.

I’ve used a few parameters of the Scrollbar such as thickness (double?) which is responsible for setting the thickness of our scrollbar, and thumbVisibility (bool?) which is responsible to make sure that the scrollbar thumb should be visible, even when a scroll is not ongoing, trackVisibility (bool?) which indicates that the scrollbar track/path should be visible, interactive (bool?) indicates that scrollbar should be interactive and give response to dragging on the thumb or tapping in the track/path area, radius (Radius?) to make scrollbar thumb’s corners rounded and some other parameters make scrollbar more interactive with the user.

ListView.builder is the most common named constructor of ListView which we use when we want to create a list recursively without writing code again and again.

ListView.builder creates a scrollable, linear array of widgets. We get here a parameter named itemCount where we pass an integer value and many times the ListView.builder will execute the same lines of code we pass to another parameter named as itemBuilder.

The code of the below project will give the best understanding with ListeView. builder.

Code File:-

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

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

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => LandingScreenProvider()),
ChangeNotifierProvider(create: (_) => FeedbackScreenProvider()),
ChangeNotifierProvider(create: (_) => RatingScreenProvider()),
],
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const LandingScreen()
),
);
}
}
  • LandingScreen.dart —
body: Container(
padding: const EdgeInsets.only(
left: padding, right: padding, bottom: padding, top: 10),
width: size.width,
height: size.height,
child: ChangeNotifierProvider.value(
value: _landingScreenProvider,
child: Consumer<LandingScreenProvider>(
builder: (_, landingScreenProvider, __) {
print(" Loaded:${landingScreenProvider.isLoaded}");
return landingScreenProvider.isLoaded
? const Center(child: CircularProgressIndicator())
: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.symmetric(
horizontal: padding)),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
GestureDetector(
onTap: () {
scaffoldKey.currentState?.openDrawer();
},
child: const BorderBox(
width: 50,
height: 50,
child:
Icon(Icons.menu, color: Colors.black),
),
),
GestureDetector(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
const SettingsScreen()));
},
child: const BorderBox(
width: 50,
height: 50,
child: Icon(Icons.settings,
color: Colors.black),
),
),
],
),
const Padding(padding: EdgeInsets.all(7)),
Text("City",
style: themeData.textTheme.bodyText2),
const Padding(padding: EdgeInsets.all(7)),
Text(
"Himachal Pradesh",
style: TextStyle(
fontSize: 50,
color: Colors.indigo.shade900,
fontWeight: FontWeight.w600),
),
const Padding(padding: EdgeInsets.all(7)),
const Divider(
// height: padding,
color: Colors.grey,
thickness: 0.7,
),
const SizedBox(
height: 5,
),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics: const BouncingScrollPhysics(),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: [
"<\$220,000",
"For Sale",
"3-4 Beds",
">1000 sqft"
]
.map((filters) =>
ChooseOption(text: filters))
.toList(),
),
),
const SizedBox(
height: 10,
),
Expanded(
child: Scrollbar(
thickness: 20,
thumbVisibility: true,
trackVisibility: true,
interactive: true,
radius: const Radius.circular(15),
child: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: imageItems.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => Dummy(
imagesListModel:
imageItems[
index])));
},
child: ListBuilder(
itemData: imageItems[index],
index: index));
}),
),
)
],
),
],
);
}),
),
),

Conclusion:-

In this article, I have explained the Scrollbar widget, its uses, and almost all the related topics of it. We understood the implementation of the scrollbar with its parameters in the demo project. You can now make your version of the demo project.

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


Module Testing In Flutter

0

Hi everyone! today we learn about Module Testing In Flutter. Module testing is a type of software testing where individual units or components of the software are tested.

The purpose of module testing is to isolate a section of code and verify its correctness. Module testing is usually performed by the development team during the early stages of software development.


Table Of Contents::

What is Module Testing?

Why does Module Testing

How to do Module Testing?

Example Tips for Module Testing

Unit Testing vs Module Testing

Challenges in Module Testing

Conclusion


What is Module Testing?

Module testing is defined as a software testing type, which checks individual subprograms, subroutines, classes, or procedures in a program. Instead of testing the whole software program at once, module testing recommends testing the smaller building blocks of the program.

Module testing is largely white-box oriented. The objective of doing Module, testing is not to demonstrate the proper functioning of the module but to demonstrate the presence of an error in the module.

Module-level testing allows to implementation of parallelism into the testing process by allowing the testing of multiple modules simultaneously.

Why does Module Testing:

Module Testing is recommended because

  • The probability of identifying errors or bugs in smaller chunks of the program becomes higher
  • Multiple modules can be tested simultaneously and hence supports parallel testing
  • The complexity of testing can be easily managed

How to do Module Testing?

  • For Module Testing, designing a Test Case is an important segment. While designing test cases for a module test, a tester has to consider two things.
  • Specification for the module
  • The module’s source code
  • Analyze the module’s logic by using one or more of the white box methods, and then supplement these test cases by applying black box methods to the modules specification
  • Once the test case is designed, the next step is to combine the module for testing. For this, the method used is either an Incremental or non-Incremental method.
  • Non-incremental method- all modules are tested independently. First, it combines all modules and then tests the whole program
  • Incremental method- each module is tested first and then gradually incremented to the tested collection. It does a step-wise retesting
  • In incremental Testing, there are two approaches — Top down and Bottom Up Testing
  • Execute the module with the selected data, requires a driver for supplying the test data, monitoring the execution, and capturing the results

Example Tips for Module Testing:

Here are a few tips to consider before performing Module Testing

  • Review test cases before using
  • Avoid confusion over the source of discrepancies
  • Use Automated Test tools
  • Examine variables that should be unchanged
  • To avoid self-tests swap modules
  • Re-use the test cases

Unit Testing vs Module Testing:

> Unit Testing:

  • Unit tests are a collection of tests written by a developer during the software development process
  • might be testing units in isolation

> Module Testing:

  • Module tests are a collection of tests written by a tester after some code has been written by a developer
  • Module testing might involve combining the unit’s test

Challenges in Module Testing:

So here we go with the top challenges in Module Testing

  • Non-incremental testing requires more work
  • Misunderstanding test doubles
  • Debugging test often
  • Need to understand the code

Conclusion:

  • In Software Engineering, Module testing (unit testing) is a process of testing the individual subprograms, subroutines, classes, or procedures in a program
  • The advantage of Module testing is that the probability of identifying errors or bugs in smaller chunks of the program becomes higher
  • For module testing method used is either an Incremental or non-Incremental method.

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

Firebase or AWS. Which cloud computing platform to use in 2023?

0

Cloud computing has become increasingly important in recent years because it allows for a wide range of tasks to be performed by programs. Web developers use various tools and languages to create impressive applications, making developer expertise essential in web and mobile app development. There are many options available in the field of cloud computing, including the ability to install and scale web and mobile apps, as well as monitor them. In recent years, there have been significant advancements in web and mobile development, and modern apps have more powerful capabilities. However, running a web or mobile app requires more than a hosting provider. Companies like Amazon and Google offer comprehensive solutions in this industry. An increasing number of developers and businesses are choosing serverless architectures, and in this article, I will compare Firebase and AWS to help your web development team determine the best option for your app.


Table of contents:

  1. Amazon Web Services (AWS)
    a. Merits of AWS
    b. Merits of AWS over Firebase
    c. Demerits of AWS
  2. Firebase
    a. Merits of Firebase
    b. Merits of Firebase over AWS
    c. Demerits of Firebase
  3. Comparison between Firebase and AWS
  4. Conclusion: Firebase or AWS, what to choose?

Amazon Web Services (AWS):

Amazon Web Services (AWS) is a cloud computing platform that provides a wide range of services such as computing, storage, networking, database, analytics, machine learning, security, and application development. These services are designed to be highly scalable, flexible, and secure, and are delivered over the internet (the cloud) to businesses of all sizes, startups, and government agencies around the world.

AWS is a pay-as-you-go service, which means that you only pay for the services you use and there is no upfront cost or long-term commitment. You can easily scale up or down the resources you use depending on your needs, and you only pay for what you use. This makes AWS a cost-effective and flexible solution for businesses that need to access a wide range of computing resources.

Some of the popular services offered by AWS include Amazon EC2 (virtual servers in the cloud), Amazon S3 (object storage), Amazon RDS (managed relational databases), Amazon Lambda (serverless computing), and Amazon EKS (managed Kubernetes). AWS also offers a variety of tools and services for building, deploying, and managing applications, such as AWS CodePipeline, AWS CodeBuild, AWS CodeDeploy, and AWS CodeStar.

In addition to these core services, AWS also offers a range of services for networking, analytics, machine learning, security, and more. These services are designed to help businesses build, deploy, and run their applications and workloads in the cloud.

Merits of AWS:

  1. Cost-effective: AWS offers a pay-as-you-go pricing model, which means you only pay for the services you use. This can be more cost-effective than buying and maintaining your hardware and infrastructure.
  2. Scalability: AWS resources can be easily scaled up or down to meet changing demands, so you can quickly and easily allocate more resources as needed.
  3. Reliability: AWS has a global infrastructure that is designed for high availability and can handle large amounts of traffic.
  4. Security: AWS provides a wide range of security tools and features to help protect your data and applications, including encryption, identity and access management, and network security.
  5. Flexibility: AWS offers a wide range of services and tools that can be easily integrated with your existing systems and applications.
  6. Innovation: AWS is constantly introducing new services and features, which can help you stay up to date with the latest technologies and best practices.
  7. Global presence: AWS has data centers located around the world, which means you can easily deploy your applications and services in multiple regions to provide low latency and high availability to your users.

Merits of AWS over Firebase:

  1. Wide range of services: AWS offers a much wider range of services than Firebase, including computing, storage, networking, database, analytics, machine learning, security, and application development. This makes AWS a more comprehensive and flexible platform for building and deploying applications.
  2. Customization: AWS allows you to customize and configure the resources you use, such as the operating system, network settings, and security policies. This can be useful if you have specific requirements or need to integrate with existing systems.
  3. Integration with other AWS services: AWS integrates with a wide range of other AWS services, such as Amazon S3, Amazon RDS, and Amazon EKS, which can be useful for building more complex and scalable applications.
  4. Greater control: With AWS, you have more control over the resources you use and how you use them. For example, you can choose which data centers to use, how to scale your resources, and how to manage access to your resources.
  5. More mature platform: AWS has been around longer than Firebase and has a larger user base, which can make it easier to find documentation, community support, and third-party tools and services.

Demerits of AWS:

  1. Cost: While AWS can be cost-effective compared to running your infrastructure, it can still be expensive, especially if you are using a large number of resources or if you have a lot of traffic.
  2. Complexity: AWS has a large number of services and features, which can be overwhelming for new users. It can take time to learn how to use all of these services and to configure them to meet your needs.
  3. Maintenance: While AWS takes care of the underlying infrastructure, you are still responsible for maintaining and managing the resources you use, such as installing patches and updates, and backing up your data.
  4. Dependence on internet connectivity: AWS is a cloud-based platform, which means you need an internet connection to access your resources. This can be an issue if you are building applications that need to work offline or in low-connectivity environments.
  5. Limited control: While AWS provides a lot of customization options, there are still some limits to what you can do. For example, you cannot directly control the underlying hardware or infrastructure, and you are subject to the terms of service and policies set by AWS.

Firebase:

Firebase has evolved from a Mobile-Backend-as-a-Service (MBaaS) platform into a comprehensive backend solution for mobile and web app development. Its services and tools allow you to quickly develop high-quality mobile and web apps without starting from scratch. Firebase is a collection of tools and software development kits (SDKs) that enable you to build, maintain, improve, and expand your apps across various mobile app development platforms, including web, iOS, and Android. Google Firebase also offers features such as file storage, analytics, identity authentication, real-time database, failure analytics, cloud storage, and push messaging. These services are generally hosted in the cloud. Firebase is a convenient cloud computing service that enables developers to connect their apps to APIs and backend cloud storage used by backend applications. Interestingly, Firebase was built on top of Google’s infrastructure. It provides SDKs for iOS, Android, and the web, making it particularly useful for front-end developers who want to build an app quickly without any backend expertise. You can also use a REST API to create a custom API.

Merits of Firebase:

  1. Efficient Identity Verification and System Security :
    Google Firebase is a platform that offers complete protection for your systems through a range of security measures, including Google Sign-in, Chrome Password Manager, and Smart Lock. With these tools, Firebase ensures that your systems are secure and that user identities are verified and protected. Additionally, Firebase simplifies the sign-in process by providing a cross-platform identity solution that covers the entire spectrum of user authentication. Overall, Firebase is a reliable and comprehensive platform for securing and managing user identities.
  2. Integrated Cloud Storage Solutions:
    Google Firebase provides a cloud storage solution that is optimized for fast and reliable uploads and downloads. It is designed to handle large volumes of user-generated content and offers easy access management options. With Firebase’s cloud storage, you can store, retrieve, and access your data quickly and efficiently, without worrying about data transfer speeds or access controls. Additionally, Firebase’s cloud storage is fully integrated with the rest of the Firebase platform, making it easy to use and manage alongside other Firebase features.
  3. Streamlined Authentication Process:
    Google Firebase is a platform that allows developers to easily and quickly set up their authentication systems without the need for extensive coding. The platform provides a range of tools and resources that make it easy to implement authentication protocols and ensure the security of your application. With Firebase, you can set up your authentication system in a matter of minutes, saving you time and resources and allowing you to focus on other aspects of app development. Overall, Firebase is a powerful and efficient tool for managing and securing your authentication system.
  4. Collaborative App Development with Firebase’s Real-Time Database:
    Firebase is a cloud-hosted NoSQL database that allows for the storage and synchronization of data in real time. This feature enables developers to access app data from any device and build powerful collaborative capabilities within their applications. Additionally, Firebase’s real-time database can be used to trigger the execution of backend code in response to events occurring within the database. This can be particularly useful for implementing real-time updates or automating tasks based on database activity.
  5. Optimizing User Engagement with Firebase’s Device Tracking and BigQuery Integration
    Firebase is a platform that provides tools for tracking a user’s activity across multiple devices, including desktop computers, web browsers, mobile phones, and tablets. With Firebase, you can easily see how users interact with your app on different devices and make informed decisions about your app’s design and functionality. Additionally, Firebase includes features that make it easier to export data from Google Analytics to BigQuery, which can be useful for developers looking to better understand their users and engage more effectively with their audience.

Merits of Firebase over AWS:

  1. Ease of use: Firebase offers a simple and intuitive interface that makes it easy for developers to get started quickly. It also provides a variety of ready-to-use features and integrations that can be easily added to a project.
  2. Real-time updates: Firebase allows developers to build real-time applications that can update data in real-time across all connected clients. This can be especially useful for applications that require fast, bidirectional communication, such as chat or gaming applications.
  3. Pricing: Firebase offers a flexible pricing model that allows developers to pay only for the resources they use. This can be more cost-effective than some of the fixed-price options offered by AWS.
  4. Integration with Google Cloud Platform: Firebase is fully integrated with the Google Cloud Platform, which means developers can use other Google services, such as BigQuery and Cloud Functions, in conjunction with Firebase.

Demerits of Firebase:

  1. Limited control: Firebase is a managed service, which means that developers do not have full control over the underlying infrastructure. This can make it more difficult to customize the platform to fit specific needs.
  2. Limited scalability: Firebase is designed to be easy to use and get started with, but it may not be the most scalable option for very large applications. Developers may need to consider other options, such as AWS if they need to scale to millions of users.
  3. Lack of support for certain workloads: Firebase is not suitable for all types of workloads. For example, it does not offer support for batch processing or high-performance computing.
  4. Vendor lock-in: Firebase is a proprietary platform, which means that developers are locked into using Google’s services. This can make it more difficult to switch to a different platform in the future if the need arises.

Comparison between Firebase and AWS:

  1. Services
    Firebase: Firebase provides several tools and services for building, scaling, and managing applications, including a real-time database, cloud storage, authentication, hosting, analytics, and push notifications.
    AWS: AWS offers a much wider range of services, including computing, storage, networking, database, analytics, machine learning, security, and application development.
  2. Customization
    Firebase: Firebase provides some customization options, such as the ability to customize the database rules and the ability to add custom domains to your hosting site.
    AWS: AWS allows you to customize and configure the resources you use, such as the operating system, network settings, and security policies.
  3. Integration
    Firebase: Firebase integrates with other Google services, such as AdMob and Google Ads, which can be useful for monetizing and marketing your application.
    AWS: AWS integrates with a wide range of other AWS services, such as Amazon S3, Amazon RDS, and Amazon EKS, which can be useful for building more complex and scalable applications.
  4. Control
    Firebase: Firebase provides several tools and features to help you manage and monitor your application, but you have limited control over the underlying infrastructure.
    AWS: With AWS, you have more control over the resources you use and how you use them. You can choose which data centers to use, how to scale your resources, and how to manage access to your resources.
  5. Cost
    Firebase: Firebase is generally less expensive than AWS, especially for small applications. However, as your usage increases, the cost can start to become comparable to AWS.
    AWS: AWS is a pay-as-you-go service, which means you only pay for the resources you use. This can be more cost-effective than buying and maintaining your hardware and infrastructure, but it can still be expensive, especially if you are using a large number of resources or if you have a lot of traffic.
  6. Learning curve
    Firebase: Firebase has a relatively shallow learning curve, with intuitive tools and features that are easy to use and get started with.
    AWS: AWS has a steeper learning curve, with a large number of services and features that can be overwhelming for new users. It can take time to learn how to use all of these services and to configure them to meet your needs.

Conclusion: Firebase or AWS, what to choose?

As already said above, Firebase is a managed service that offers a simple and intuitive interface, making it easy for developers to get started quickly. It is well-suited for real-time applications that require fast, bidirectional communication, such as chat or gaming apps. Firebase also offers a flexible pricing model and is fully integrated with the Google Cloud Platform, allowing developers to use other Google services in conjunction with Firebase.

However, Firebase has some limitations to be aware of. It does not offer full control over the underlying infrastructure, so it may not be as customizable as some other platforms. It may not be the most scalable option for very large applications and does not support certain types of workloads, such as batch processing or high-performance computing. In addition, Firebase is a proprietary platform, which means that developers are locked into using Google’s services and may have difficulty switching to a different platform in the future.

On the other hand, AWS is a comprehensive cloud computing platform that offers a wide range of services and robust infrastructure. It is highly scalable and can support millions of users. AWS is also well-suited for a variety of workloads, including batch processing and high-performance computing. However, it may be more complex to set up and use than Firebase, and it may have higher upfront costs due to its fixed-price pricing model.

Ultimately, the best choice will depend on your specific needs and requirements. It is important to carefully evaluate your options and consider consulting with a cloud computing expert to help you make the right decision.

Thanks for reading this article.
If I got something wrong? Let me know in the comments. I would love to improve.


From Our Parent Company Aeologic

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

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

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

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

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

Parallax Scrolling Effect with Flutter

0

A parallax scrolling effect is attained by pushing the background image very slightly toward the opposite direction of the whole list. Let’s know more about it.


Table of Contents :

Parallax Effect — Introduction

What is a Stack widget? — Explained

Constructor of Stack Class

Implementation in code

Code Implementation

Conclusion


Parallax effect

Parallax scrolling is a website technique where we make our background move at a little slower pace than the foreground we make. This is a 3D effect as the user scrolls down the site, putting in a sense of depth and forming a more mesmeric experience while browsing.

Our eyes recognize objects close to us comparatively larger than those far away from our eyes. We perceive distant objects as if they are moving very slowly. Parallax bounds the same idea as human eyes which is a so-called optical illusion.

Flutter makes it very easy to implement the parallax effect in our apps by using a few widgets, such as Stack, Positioned, etc. We’re going to use Stack and Positioned widget in the demo project below. With the help of flutter widgets here we quickly can implement parallax scrolling.

What is a Stack widget?

It is a widget in Flutter SDK which allows us to make layers of widgets by putting one over the other.

This class is significant if you want to overlap several children simply. It is like putting objects in a single bucket one after the other(First goes in, last comes out). Similarly, if we assemble the same example pattern in a flutter, we could imagine having a few texts and an image, overlaid with a gradient and an elevated button attached at the bottom.

It gets mixed very smoothly and makes the UI much more interactive than before.

Constructor of Stack Class:

Stack(
{Key key,
AlignmentGeometry alignment: AlignmentDirectional.topStart,
TextDirection textDirection,
StackFit fit: StackFit.loose,
Overflow overflow: Overflow.clip,
Clip clipBehavior: Clip.hardEdge,
List<Widget> children: const <Widget>[]}
)

Implementation in code:

Stack(
children: [
Image.asset(
ImageUtils.roundShape,
width: double.infinity,
),
Container(
height: 51.h,
// width: 270.w,
decoration: BoxDecoration(
color: ColorUtils.color373856,
borderRadius: BorderRadius.circular(
45.r,
),
),
);
SvgPicture.asset(
ImageUtils.scanIcon,
height: 51.h,
width: 51.w,
),
],
);

The children i.e., Image, Container, and SvgPicture widgets will be overlaid one over the other. Top — > SvgPicture widget, Bottom — > Image widget.

We’re also using the Positioned widget in this. Positioned widget is a widget that controls where a child of a Stack widget is going to be positioned. For example :

Stack(
children: [
Container(
height: 250,
child: Image.network(
"https://i.pinimg.com/originals/4f/39/10/4f39103da156fb7e479abd6355932e88.jpg",
loadingBuilder: (context, child, loadingProgress) {
if (loadingProgress == null) {
return child;
} else {
return const Center(
child: CircularProgressIndicator());
}
}, fit: BoxFit.fill),
),
Positioned(
bottom: 20,
left: 20,
child: ClipRRect(
borderRadius: BorderRadius.circular(60),
child: Image.network(
"https://scontent.fdel3-2.fna.fbcdn.net/v/t39.30808-6/301901141_372422665106709_6958811342740638978_n.jpg?_nc_cat=107&ccb=1-7&_nc_sid=09cbfe&_nc_ohc=LgtpoTtlA7QAX--bEd1&_nc_ht=scontent.fdel3-2.fna&oh=00_AT9ZAOvxE80tiN7MQ5xUQ5SVLRiLhUpQwP5egfuSNkmrAA&oe=6351DA3E",
loadingBuilder: (context, child, loadingProgress) {
if (loadingProgress == null) {
return child;
} else {
return const Center(
child: CircularProgressIndicator());
}
},
fit: BoxFit.fill,
height: 75,
width: 80,
),
))
]
);

Here Positioned widget is for setting the fixed position of the child, i.e., the ClipRRect widget. For this, we’d be using named parameters such as top, bottom, left, right, etc. In the above example, bottom: 20 and left: 20 parameters are being used which means the child widget will be positioned this much distance from the left and bottom of the stack. Then the other parameters will occupy the rest of the distance (from top and right).

In the further demo project, we’ll be dealing with ListView widget as our Scrollable. ListView widget is the most commonly used ScrollView widget where its children get displayed one after another in the scroll direction.

Role of ListView in our demo:

In our project, the ListView widget that has a child of a Container widget is going to be responsible to form the background for all the further children of Stack

.ListView(
children: <Widget>[
Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment(0.5, 0.0),
colors: [
Color.fromRGBO(130, 0, 94, 1),
Colors.lightBlue
],
tileMode: TileMode.mirror)),
height: 1200)
],
),

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

Over this, we’ll add some images & texts, and then form a parallax effect using them.

Code Implementation:-

main.dart

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

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

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const ParallaxEffectScreen(),
);
}
}

ParallaxEffectScreen.dart

class ParallaxEffectScreen extends StatefulWidget {
const ParallaxEffectScreen({Key? key}) : super(key: key);
@override
State<ParallaxEffectScreen> createState() => _ParallaxEffectScreenState();
}

class _ParallaxEffectScreenState extends State<ParallaxEffectScreen> {
String? asset;
double divOne = 0;
double divFive = 0;

@override
Widget build(BuildContext context) {
return Scaffold(
body: NotificationListener(
onNotification: (notify) {
if (notify is ScrollUpdateNotification) {
setState(() {
divOne += notify.scrollDelta! / 1;
divFive += notify.scrollDelta! / 5;
});
}
return true;
},
child: Stack(
children: <Widget>[
ListView(
children: <Widget>[
Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment(0.5, 0.0),
colors: [
Color.fromRGBO(130, 0, 94, 1),
Colors.lightBlue
],
tileMode: TileMode.mirror)),
height: 1200)
],
),
ParallaxText(
colour: Colors.white,
left: 170 - divOne * 3,
top: 120 + divFive,
text: "Demo of"),
ParallaxText(
colour: Colors.white,
left: 20 + divOne * 2,
top: 400 + divFive / 2,
text: "Parallex\n Scrolling"),
ParallaxImage(
left: 20,
top: 100 - divOne,
height: 200,
width: 200,
asset: "photo6",
widget: ParallaxText(
colour: const Color.fromRGBO(130, 0, 94, 1),
left: 150 - divOne * 3,
top: 20 + divOne + divFive,
text: "Demo of",
)),
ParallaxImage(
left: 200 - divOne,
top: 350 - divOne,
height: 300,
width: 300,
asset: "photo7",
widget: ParallaxText(
colour: const Color.fromRGBO(130, 0, 94, 1),
left: -180 + divOne * 3,
top: 50 + divOne + divFive / 2,
text: "Parallax\n Scrolling",
)),
ParallaxText(
colour: Colors.white,
left: divFive,
top: 720 - divOne,
text: "Be creative",
),
ParallaxImage(
left: 95,
top: 700 - divOne,
height: 400,
width: 230,
asset: "photo3",
widget: ParallaxText(
colour: const Color.fromRGBO(130, 0, 94, 1),
left: -95 + divFive,
top: 20,
text: "Be creative",
))
],
),
),
);
}
}

Here ParallaxText() is a constructor of a Custom widget made for the arrangement of texts over the screen(as they internally contain Positioned widgets). Similarly, the ParallaxImage() is a constructor of a Custom widget that will be responsible for the arrangement of Images over the screen.

ParallaxText.dart

class ParallaxText extends StatelessWidget{

const ParallaxText({
Key? key,
required this.left,
required this.top,
required this.text,
required this.colour,
}) : super(key: key);

final double left;
final double top;
final String text;
final Color colour;

@override
Widget build(BuildContext context) {
return Positioned(
left: left,
top: top,
child: Text(text, style: TextStyle(color: colour, fontWeight: FontWeight.w900, fontSize: 60.0, fontFamily:"Helvetica")
),
);
}
}

ParallaxImage.dart

class ParallaxImage extends StatelessWidget{

const ParallaxImage({
Key? key,
required this.left,
required this.top,
required this.asset,
required this.height,
required this.width,
required this.widget,
}) : super(key: key);

final double left;
final double top;
final String asset;
final double height;
final double width;
final Widget widget;

@override
Widget build(BuildContext context) {
return Positioned(
left: left,
top: top,
child: Container(decoration: BoxDecoration(image: DecorationImage(
fit: BoxFit.cover,
image: ExactAssetImage("assets/images/$asset.png")
),
borderRadius: BorderRadius.circular(12.0)),
height: height,
width: width,
child: Stack(children: <Widget>[
widget
],),)
);
}
}

Here, the Positioned widget helps its child to get positioned over the stack according to the parameters it’s receiving.

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

Final Output

Conclusion:

In this article, we’ve learned how to display a list of parallax scrolling images/texts. Now you can try it in your project and make it more fun to work with.

❤ ❤ 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 Facebook, GitHub, Twitter, 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.


Navigate With GoRouter In Flutter

0

A declarative routing package for Flutter that uses the Router API to provide a convenient, URL-based API for navigating between different screens.


Table Of Content

Introduction

Add Dependency

Features

Implementation

Conclusion

GitHub Link


Introduction:

The goal of the go_router package is to simplify the use of the Router in Flutter as specified by the MaterialApp.router constructor. By default, it requires an implementation of the Router Delegate and Route Information Parser classes. These two implementations themselves imply the definition of a custom type to hold the app state that drives the creation of the Navigator. You can read an excellent blog post on these requirements on Medium. This separation of responsibilities allows the Flutter developer to implement several routing and navigation policies at the cost of complexity.


Add Dependency:

Open the terminal in your Flutter project. Then run the following command to install the go_router package in your Flutter Project.$ flutter pub add go_router

or you will add this line to your package’s pubspec. ymal file and run “flutter pub get”

dependencies:
go_router: ^6.0.1

Features:

GoRouter has many features:-

  • > Parsing path and query parameters using a template syntax (for example, “user/:id’).
  • > Displaying multiple screens for a destination (sub-routes).
  • > Redirection support — you can re-route the user to a different URL based on application state, for example to a sign-in when the user is not authenticated.
  • > Backwards compatibility with Navigator API
  • > Support for both Material and Cupertino apps

Implementation:

Hello Everyone…!!!! Today we learn about routing in the flutter application. To integrate go_router in your app first you have to add MaterialApp.router in the place of the MaterialApp. This constructor accepts many properties like routeInformationParser, routerDelegate, etc.

MaterialApp.router(
debugShowCheckedModeBanner: false,
routeInformationParser:
NyAppRouter.returnRouter(false).routeInformationParser,
routerDelegate: NyAppRouter.returnRouter(false).routerDelegate,
);

After that, we create an app_route_config.dart. In this file, we pass all the routes. First, we add the default route which is the home page. In routes, we add a name, path ad pageBuilder. After that, we create a route for the profile page in which we pass the userId and userName. And we also create GoRoute for the about page and contact us page.

class NyAppRouter {
static GoRouter returnRouter(bool isAuth) {
GoRouter router = GoRouter(
routes: [
GoRoute(
name: MyAppRouteConstants.homeRouteName,
path: '/',
pageBuilder: (context, state) {
return const MaterialPage(child: Home());
},
),
GoRoute(
name: MyAppRouteConstants.profileRouteName,
path: '/profile/:username/:userid',
pageBuilder: (context, state) {
return MaterialPage(
child: Profile(
userid: state.params['userid']!,
username: state.params['username']!,
));
},
),
GoRoute(
name: MyAppRouteConstants.aboutRouteName,
path: '/about',
pageBuilder: (context, state) {
return const MaterialPage(child: About());
},
),
GoRoute(
name: MyAppRouteConstants.contactUsRouteName,
path: '/contact_us',
pageBuilder: (context, state) {
return const MaterialPage(child: ContactUS());
},
)
],
errorPageBuilder: (context, state) {
return const MaterialPage(child: ErrorPage());
},
);
return router;
}
}

And also add errorPageBuilder in which we return MaterialPage and pass ErrorPage as a child. and return the router. This is how we create the routes for navigators.

We also create the route constants for GoRouters. In which we pass all the routes as a string.

class MyAppRouteConstants {
static const String homeRouteName = 'home';
static const String aboutRouteName = 'about';
static const String profileRouteName = 'profile';
static const String contactUsRouteName = 'contact_us';
}

At last, we create the UI of the project and in the UI part, we also learn the go_router and how to navigate the UI. In-home. dart we return the scaffold and pass the appbar in which we pass the title. Pass the Column in the body and add the buttons by which we navigate from one screen to another screen.

We can navigate in many ways like push, pushNamed in which we pass the params like userName and UserId or we can directly pass the path of the route which we already defined in the route_config.dart file. This is how we use go_router. I hope you learn many things like how to create paths or routes and how to pass params easily.

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('Go Router Demo'),
),
body: Column(
children: [
ElevatedButton(
onPressed: () {
GoRouter.of(context).push(Uri(path: '/about').toString());
},
child: const Text('About Page')),
ElevatedButton(
onPressed: () {
GoRouter.of(context)
.pushNamed(MyAppRouteConstants.profileRouteName, params: {
'username': 'Text user',
'userid': 'uhfhfhfdghfk'
});
},
child: const Text('Profile Page')),
ElevatedButton(
onPressed: () {
GoRouter.of(context)
.pushNamed(MyAppRouteConstants.contactUsRouteName);
},
child: const Text('ContactUs Page')),
],
),
);
}

Conclusion:

In this article, we learn how to implement go_router in Flutter Application. We learn many things like how to create the config file and how to pass params to another screen and many things.

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

Find the source code of the Navigate With GoRouter In Flutter:

GitHub – flutter-devs/go_router_demo-
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…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 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.


OTP Autofill in Flutter UI

0

Hey friends. Today we’re going to discuss how can we fill up the OTP fields of our screen(Flutter UI) automatically as the OTP SMS comes.


Table of Contents :

OTP Autofilling — Introduction and Uses

Firebase Phone Authentication

Code Implementation

OTP Autofill —step by step implementation

Code File

Conclusion

Github Link


Introduction and Uses:-

These days we see several times that as we approach getting signed-in in many applications we need to verify our phone numbers. Although, we can do so in mainly two ways, either by making a phone call or by an OTP — sent as sms to our phone numbers.

So along with that, we have also noticed, that the OTP which comes with the sms got filled up automatically in the OTP fields which makes UI more user-friendly. Well, how does that happen? I’m going to answer the question with the help of this article along with my demo project.

In this session, we’d be using the most commonly used package for such purposes, that is sms_autofill.

Working with this package made it comparatively easier and faster to get my expected output. We just need to follow a few steps to make it work properly throughout our project which we’ll discuss later in this article.

To get the OTP sms, I’ve used Firebase Phone Authentication. To achieve that we first need to create a Firebase project in Firebase Console. Once you have created one, make sure that you enable the Phone sign-in method in the Authentication section.

Firebase Phone Authentication:-

Here’s how we do it:-

To know more, you may go to the Apple, Android, or web options according to the project environment in which you build the project. For me it was Android.

Save it as you enable it. It will look like this

Now firstly, we need to send an OTP sms to the entered mobile number.

Code Implementation:-

CommonUtils.dart

class CommonUtils {
static String verify = "";

static Future<String> firebasePhoneAuth(
{required String phone, required BuildContext context}) async {
try {
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phone,
verificationCompleted: (PhoneAuthCredential credential) {
print("Phone credentials $credential");
},
verificationFailed: (FirebaseAuthException e) {
print("Verification failed $e");
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Verification Failed! Try after some time.")));
},
codeSent: (String verificationId, int? resendToken) async {
CommonUtils.verify = verificationId;
print("Verify: $verificationId");
},
codeAutoRetrievalTimeout: (String verificationId) {},
);
return CommonUtils.verify;
} catch (e) {
print("Exception $e");
return "";
}
}
}

Here, we’ll pass the phone number (fetched by the TextEditingController) to the phone argument of this function.

We used Future<String> as the return type because we are going to return the verification ID that we get during the process of sending OTP. Further, this verification ID will be needed in the OTP screen.

PhoneAuthCredential credential =
PhoneAuthProvider.credential(
verificationId: CommonUtils.verify,
smsCode: otpCode);
await auth.signInWithCredential(credential);
setState(() {
isLoaded = false;
});
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => const HomeScreen()));
}

This is a snippet from the OtpScreen.dart where we are using the verification ID we extracted from CommonUtils.firebasePhoneAuth() method. Along with that, we pass our smsCode received. It then matches OTP which was sent and the OTP which is being passed in smsCode along with the verification ID. If they match, we successfully will be authorized to get through the other page (HomeScreen.dart).

OTP Autofill:-

Now let’s get through the steps to implement otp-auto-filling

Import the latest version of the sms_autofill package in pubspec.yaml file

dependencies:
sms_autofill: ^2.2.0

Go to >android >app >build.gradle file and change minSdkVersion from 16 to 19

defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.otp_autofill_demo"
// You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
minSdkVersion 19
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}

Add listner listenForCode() method inside initState() method to listen otp sms as soon as possible.

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

void _listenOtp() async {
await SmsAutoFill().listenForCode();
print("OTP Listen is called");
}

Use the PinFieldAutoFill() widget as our OTP field. You can apply decoration to it to make it more attracting. I’ve used BoxLooseDecoration() constructor to decorate fields.

PinFieldAutoFill(
currentCode: otpCode,
decoration: const BoxLooseDecoration(
radius: Radius.circular(12),
strokeColorBuilder: FixedColorBuilder(
Color(0xFF8C4A52))),
codeLength: 6,
onCodeChanged: (code) {
print("OnCodeChanged : $code");
otpCode = code.toString();
},
onCodeSubmitted: (val) {
print("OnCodeSubmitted : $val");
},
)

Override dispose() method to unregister stream listener. This is a very significant step as the stream should be closed once we’re done using it. Otherwise, we could face memory leakage problem.

@override
void dispose() {
SmsAutoFill().unregisterListener();
print("Unregistered Listener");
super.dispose();
}

Well, by this we’ve completed all the steps we needed to do. Further will be the whole code implementation of the demo project.

Code File:-

main. dart

void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}

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

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const LoginScreen(),
);
}
}

LoginScreen.dart

class LoginScreen extends StatefulWidget {
static String verify = "";

const LoginScreen({Key? key}) : super(key: key);

@override
State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
final _formKey = GlobalKey<FormState>();
final _phoneController = TextEditingController();
final _countryCodeController = TextEditingController();
Color focusBorderColor = Colors.black12;
Color underlineColor = Colors.grey.shade200;
RegExp regExp = RegExp(r'^[0]?[6789]\d{9}$');
RegExp countryRegExp = RegExp(r'^\+?(\d+)');
bool divider = false;
bool isLoaded = false;

int validatePhone(String phone) {
String pattern = r'^[0]?[6789]\d{9}$';
RegExp regExp = RegExp(pattern);
if (phone.isEmpty) {
return 1;
} else if (phone.length < 10) {
return 2;
} else if (!regExp.hasMatch(phone)) {
return 3;
} else {
return 0;
}
}

@override
Widget build(BuildContext context) {
return ColorfulSafeArea(
color: const Color(0xFF8C4A52),
child: SafeArea(
child: Scaffold(
backgroundColor: isLoaded ? Colors.white : const Color(0xFF8C4A52),
body: isLoaded
? const Center(child: CircularProgressIndicator())
: CustomScrollView(
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Column(
children: [
Container(
alignment: Alignment.center,
padding: const EdgeInsets.only(top: 50),
child: Container(
height: 50,
)),
const SizedBox(
height: 25,
),
WhiteContainer(
headerText: "Login",
labelText:
"Please enter your 10 digit phone no to proceed",
child: BorderBox(
margin: false,
padding: const EdgeInsets.symmetric(
horizontal: 15),
color: Colors.grey.shade200,
height: 60,
child: Form(
key: _formKey,
child: Row(
children: [
BorderBox(
height: 100,
width: 55,
padding:
const EdgeInsets.symmetric(
vertical: 2,
horizontal: 8),
color: Colors.grey.shade200,
margin: false,
child: TextFormField(
controller:
_countryCodeController,
textInputAction:
TextInputAction.next,
onChanged: (value) {
if (!countryRegExp
.hasMatch(value)) {
setState(() {
focusBorderColor =
Colors.red.shade900;
underlineColor =
focusBorderColor;
});
} else {
setState(() {
focusBorderColor =
Colors.green.shade700;
underlineColor =
focusBorderColor;
});
}
if (value.length == 4) {
FocusScope.of(context)
.nextFocus();
}
},
validator: (value) {
if (value!.isEmpty) {
return "Code?";
} else if (!countryRegExp
.hasMatch(value)) {
return "Invalid";
}
},
style: TextStyle(fontSize: 19),
keyboardType:
TextInputType.phone,
inputFormatters: [
LengthLimitingTextInputFormatter(
4)
],
decoration: InputDecoration(
hintText: "+91",
hintStyle: TextStyle(
color:
Colors.grey.shade400),
enabledBorder:
UnderlineInputBorder(
borderSide: BorderSide(
color: underlineColor),
),
focusedBorder:
UnderlineInputBorder(
borderSide: BorderSide(
color:
focusBorderColor),
),
),
)),
const Padding(
padding: EdgeInsets.symmetric(
vertical: 7.0),
child: VerticalDivider(
thickness: 2,
),
),
BorderBox(
height: 100,
width: 250,
color: Colors.grey.shade200,
padding:
const EdgeInsets.symmetric(
vertical: 2,
horizontal: 8),
margin: false,
child: TextFormField(
controller: _phoneController,
validator: (value) {
int res =
validatePhone(value!);
if (res == 1) {
return "Please enter number";
} else if (res == 2) {
return "Please enter 10 digits phone number";
} else if (res == 3) {
return "Please enter a valid 10 digits phone number";
} else {
return null;
}
},
style: const TextStyle(
fontSize: 19),
keyboardType:
TextInputType.phone,
onChanged: (value) {
if (value.isEmpty) {
FocusScope.of(context)
.previousFocus();
} else if (value.length ==
10) {
FocusScope.of(context)
.unfocus();
}
},
inputFormatters: [
LengthLimitingTextInputFormatter(
10),
FilteringTextInputFormatter
.digitsOnly
],
decoration: InputDecoration(
border: InputBorder.none,
hintText: "XXXXXXXXXX",
hintStyle: TextStyle(
color: Colors
.grey.shade400)),
)),
],
),
))),
],
),
),
],
),
bottomNavigationBar: Container(
padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 20),
color: Colors.white,
child: GestureDetector(
onTap: () async {
setState(() {
isLoaded = true;
});
if (_formKey.currentState!.validate()) {
var appSignature = await SmsAutoFill().getAppSignature;
LoginScreen.verify = await CommonUtils.firebasePhoneAuth(
phone: _countryCodeController.text +
_phoneController.text,
context: context);
Future.delayed(const Duration(seconds: 5)).whenComplete(() {
setState(() {
isLoaded = false;
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => OtpScreen(
phone: _countryCodeController.text +
_phoneController.text)));
print("App Signature : $appSignature");
});

});
}
},
child: const BorderBox(
margin: false,
color: Color(0xFF8C4A52),
height: 50,
child: Text(
"Proceed",
style: TextStyle(fontSize: 18, color: Colors.white),
),
)),
),
),
));
}
}

OtpScreen.dart

class OtpScreen extends StatefulWidget {
final String phone;

const OtpScreen({Key? key, required this.phone}) : super(key: key);

@override
State<OtpScreen> createState() => _OtpScreenState();
}
class _OtpScreenState extends State<OtpScreen> {
String otpCode = "";
String otp = "";
bool isLoaded = false;
final _formKey = GlobalKey<FormState>();
final FirebaseAuth auth = FirebaseAuth.instance;

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

@override
void dispose() {
SmsAutoFill().unregisterListener();
print("Unregistered Listener");
super.dispose();
}

void _listenOtp() async {
await SmsAutoFill().listenForCode();
print("OTP Listen is called");
}

@override
Widget build(BuildContext context) {
return ColorfulSafeArea(
color: const Color(0xFF8C4A52),
child: SafeArea(
child: Scaffold(
backgroundColor: isLoaded ? Colors.white : const Color(0xFF8C4A52),
body: isLoaded
? const Center(child: CircularProgressIndicator())
: CustomScrollView(
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Column(
children: [
Container(
alignment: Alignment.center,
padding: const EdgeInsets.only(top: 50),
child: Container(
height: 50,
)),
const SizedBox(
height: 25,
),
WhiteContainer(
headerText: "Enter OTP",
labelText:
"OTP has been successfully sent to your \n ${widget.phone}",
child: Container(
height: 70,
width: MediaQuery.of(context).size.width,
child: Column(
children: [
PinFieldAutoFill(
currentCode: otpCode,
decoration: const BoxLooseDecoration(
radius: Radius.circular(12),
strokeColorBuilder: FixedColorBuilder(
Color(0xFF8C4A52))),
codeLength: 6,
onCodeChanged: (code) {
print("OnCodeChanged : $code");
otpCode = code.toString();
},
onCodeSubmitted: (val) {
print("OnCodeSubmitted : $val");
},
)

],
),
),
),
],
),
),
],
),
bottomNavigationBar: Container(
padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 30),
color: Colors.white,
child: GestureDetector(
onTap: () async {
print("OTP: $otpCode");
setState(() {
isLoaded = true;
});
if (_formKey.currentState!.validate()) {
try {
PhoneAuthCredential credential =
PhoneAuthProvider.credential(
verificationId: CommonUtils.verify,
smsCode: otpCode);
await auth.signInWithCredential(credential);
setState(() {
isLoaded = false;
});
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => const HomeScreen()));
} catch (e) {
setState(() {
isLoaded = false;
});
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Wrong OTP! Please enter again")));
print("Wrong OTP");
}
}
},
child: const BorderBox(
margin: false,
color: Color(0xFF8C4A52),
height: 50,
child: Text(
"Continue",
style: TextStyle(fontSize: 18, color: Colors.white),
),
),
),
),
)));
}
}

You can build your home page as you like.

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

Conclusion:-

In this article, we’ve learned how to autofill OTP from OTP sms. Moreover, we also got to know about Firebase Phone Authentication and implemented it in the project.

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

Find the source code of the OTP Autofill :

GitHub – flutter-devs/OTP_Autofill
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…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.


Flame with Flutter

0

The Flame Engine aims to provide a complete set of solutions for most of the common problems that games developer might face in the flutter environment.

This article will deliver a quality introduction to the Flutter Flame game engine. You’ll learn how to build a Flutter Flame game, load sprites, and add animations. In the further project, we shall talk about animations made with Flutter Flame.


Table of Contents :

Flutter — Introduction

Flutter Flame

Installation

Code Implementation

Component

Code File

Final Output

Conclusion

Github Link


Introduction:

Flutter is an open-source framework created by Google where we craft various attractive applications for the Android, iOS, web, etc platforms from a single code base. Flutter uses a client-optimized language called Dart that makes faster apps on any platform. It is a much easier approach than traditional methods.

Flutter makes it easy to develop beautiful, interactive, and user-friendly interfaces(UI). Although, Flutter is a framework that is used for both frontend and backend development. But because of its adorable performance in frontend developers mostly use Flutter for Frontend development.

The Flutter team is dedicated to providing the ability to all kinds of developers to build applications in a minimal amount of time and release them effortlessly. For instance, Game developers are now capable of crafting beautiful game apps without taking care of performance issues, load times, and app sizes problems.

Flame:

It is a 2D game engine by which we develop various 2D game applications that run on top of flutter. We get so many useful & amazing features of it such as

  • Game loop
  • A component/object system(Flame Component System(FCS))
  • Collision detection
  • Images, sprites, sprite sheets, and animations.
  • Input/gestures handling
  • General utilities that make development easier.

Installation:-

Initially, you need to install Flame to implement it in your project. For that, we need to add its package with the latest version of it in pubspec.yaml file:

dependencies:
flame: ^1.6.0

Code Implementation:-

To attach a Game instance in our Flutter tree, we need to give the charge to the widget called GameWidget. Or in simpler words, we will wrap our game with GameWidget at initials.

void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
runApp(GameWidget(game: Game()));
}

Here Game() is the game instance that GameWidget() will render over the screen. “Game” extends the FlameGame class.

class Game extends FlameGame with HasTappables {
@override
Future<void>? onLoad() {
super.onLoad();
}

FlameGame is a more absolute and opinionated implementation of Game. Extending it makes the developer able to add his game logic or he can keep the logic in the child Component.

FlameGame is based on the Flame Component System (also called FCS). This is the base class mostly recommended to use for most games that are made with Flame.

Component:

Everything we see on top of the screen is all components. For instance, background image, all the characters/objects on the screen, etc.

All components get inherited from the abstract class Component directly or indirectly.

Every Component has a few methods that you can implement optionally while using FlameGame the class. If you are not using FlameGame, you can implement these methods on your game loop if you need.

Few generally used components:

  • PositionalComponent — This class represents a positioned object over the screen, which could be a floating rectangle or a rotating sprite.

Constructor:-

PositionComponent({
Vector2? position,
Vector2? size,
Vector2? scale,
double? angle,
double nativeAngle = 0,
Anchor? anchor,
Iterable<Component>? children,
int? priority,
})
  • FlameGame — It is based on the Flame Component System (FCS). It is the most recommended component to be extended to work with Flame.

Constructor:-FlameGame({
Iterable<Component>? children,
Camera? camera,
})

  • SpriteComponentSpriteComponent is the most commonly used implementation of PositionComponent, and it can be built with a Sprite .

Constructor:-

SpriteComponent({
Sprite? sprite,
Paint? paint,
Vector2? position,
Vector2? size,
Vector2? scale,
double? angle,
double? nativeAngle,
Anchor? anchor,
Iterable<Component>? children,
int? priority,
})
  • SpriteAnimationComponent — This class is used to represent sprites containing Components that run in a single cyclic animation. I’ll be using it in the further project file for the animation making.

Constructor:-

SpriteAnimationComponent({
SpriteAnimation? animation,
bool? removeOnFinish,
bool? playing,
Paint? paint,
Vector2? position,
Vector2? size,
Vector2? scale,
double? angle,
double? nativeAngle,
Anchor? anchor,
Iterable<Component>? children,
int? priority,
})

There are so many other classes that extend Component directly or indirectly and use its methods by overriding it.

Code File:

The project is all about an animated user interface using a flame. All the related file snippets are presented below:

main. dart

void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
runApp(GameWidget(game: GameComponent()));
}

GameComponent.dart

class GameComponent extends FlameGame with HasTappables {
MovementState movementState = MovementState.running;
late SpriteSheet spriteSheet;
late SpriteAnimation spriteAnimation;
DialogButton dialogButton = DialogButton();
final Vector2 buttonSize = Vector2(100.0, 100.0);

SpriteAnimationComponent animationComponent = SpriteAnimationComponent(
size: Vector2(402 * 0.7, 202 * 0.7), position: Vector2(100, 180));
BackgroundComponent backgroundComponent = BackgroundComponent();

@override
Future<void>? onLoad() async {
super.onLoad();
await loadAnimations();
button();
add(backgroundComponent);
add(animationComponent);
add(dialogButton);
}

Future<void> loadAnimations() async {
if (movementState == MovementState.running) {
spriteSheet = SpriteSheet(
image: await images.load("cat_final.png"),
srcSize: Vector2(402, 202));
spriteAnimation =
spriteSheet.createAnimation(row: 0, stepTime: 0.1, from: 0, to: 11);
} else {
spriteSheet = SpriteSheet(
image: await images.load("cat_final.png"),
srcSize: Vector2(402, 202));
spriteAnimation =
spriteSheet.createAnimation(row: 0, stepTime: 0.35, from: 12, to: 18);
}
animationComponent.animation = spriteAnimation;
}

void button() async {
dialogButton
..sprite = await loadSprite("button.png")
..size = buttonSize
..position =
Vector2(size[0] - buttonSize[0] - 10, size[1] - buttonSize[1] - 10);
}

@override
void update(double dt) {
super.update(dt);
if (dialogButton.isTapped) {
// print("Tapped?${dialogButton.isTapped}");
movementState = MovementState.idle;
loadAnimations();
return;
} else {
movementState = MovementState.running;
// loadAnimations();
return;
// }
}
}
}

DialogButton.dart

class DialogButton extends SpriteComponent with Tappable {
MovementState movementState = MovementState.running;
GameComponent? game;
bool isTapped = false;
@override
bool onTapDown(TapDownInfo info) {
try {
print("Pressed");
isTapped = !isTapped;
isTapped ? movementState = MovementState.idle : movementState = MovementState.running;
print(movementState);
return true;
} catch(e) {
print("Something went wrong $e");
return false;
}
}
}

BackgroundComponent.dart

class BackgroundComponent extends SpriteComponent
with HasGameRef<GameComponent> {
@override
Future<void> onLoad() async {
await super.onLoad();
sprite = await gameRef.loadSprite("background.png");
size = gameRef.size;
}
}

You can download sprite sheets and make your animation UI. Few are here.

Final Output:-

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

As we click the DialogButton component, we are changing the sprite sheet limits from 0–11(running state) to 12–18(sitting state).

Conclusion:-

In this article, we’ve learned how to work will package flame to encounter animation in our application. We commonly use this package for developing 2D games but it’s indeed a good choice for the making of animations too in our 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.


Find the source code of flame_flutter:

https://github.com/flutter-devs/flame_flutter


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.


Redux State Management in Flutter

0

State management is one of the most important aspects of app development. In a large and complex application, keeping track of the state of different widgets and managing the flow of data can quickly become a challenging task. This is where Redux comes in.

Redux is a state management library that is widely used in React and React Native applications. It is also a popular choice for state management in Flutter, a UI toolkit for building natively compiled applications for mobile, web, and desktop.

It provides a centralized store for storing the state of an application, and it follows the unidirectional data flow pattern. In Flutter, Redux can be used to manage the state of an application, making it easier to understand, maintain, and scale.

In this blog, we’ll explore how to integrate Redux into a Flutter application and understand the key concepts of Redux.


Table Of Contents::

What is Redux

Why use Redux in Flutter

Integrating Redux into a Flutter application

Conclusion


What is Redux?

Redux is a predictable state management library that is based on the principles of Flux architecture. It is designed to make it easy to manage the state of an application in a centralized and consistent way. The core concepts of Redux are:

  1. State: The state of an application is the data that changes over time, such as user data, API responses, or UI state.
  2. Actions: Actions are events that are dispatched from the view layer to modify the state of the application. Actions have a type and can also have payload data.
  3. Reducer: The reducer is a pure function that takes the current state and an action as inputs and returns the updated state. The reducer defines how the state should be updated based on the action type.
  4. Store: The store is the central place where the state of the application is stored. The store is created by passing the reducer function to it.

By following these core concepts, Redux makes it easy to manage the state of an application consistently and predictably.

Why use Redux in Flutter?

Flutter provides a rich set of built-in widgets and tools for building complex UIs. However, as the size and complexity of a Flutter application grow, it becomes more challenging to manage the state of the application. This is where Redux comes in. By using Redux, you can centralize the state of your application and make it easier to manage.

Some of the benefits of using Redux in Flutter are:

  1. Predictable state management: With Redux, the state of the application is managed in a centralized and consistent way. This makes it easier to understand how the state changes over time and debug any issues that may arise.
  2. Scalability: As the size and complexity of a Flutter application grows, Redux makes it easier to manage the state of the application. By following the core concepts of Redux, you can quickly scale the state management of your application.
  3. Reusable code: By centralizing the state of the application, you can write reusable code that can be shared across different parts of the application.
  4. Easy to test: Because the reducer is a pure function, it is easy to write automated tests. This makes it easier to ensure that the state of the application is being updated correctly

Integrating Redux into a Flutter application:

In Flutter, there are several packages available for implementing Redux, such as flutter_redux and redux_thunk. To get started with Redux in Flutter, you need to install the flutter_redux package and create a store for your application.

dependencies:
flutter_redux: ^7.0.0

The store is created using the createStore() function, which takes the initial state of the store and a reducer as arguments. The initial state is a plain Dart object, and the reducer is a Dart function that takes the store’s current state and action and returns the next state of the store.

  1. Define your application state and action:
class AppState {
int counter;

AppState({this.counter = 0});
}

enum Actions { incrementCounter }

2. Create the reducer:

AppState appReducer(AppState state, dynamic action) {
if (action == Actions.incrementCounter) {
return AppState(counter: state.counter + 1);
}
return state;
}

3. Create the store:

final store = Store<AppState>(
appReducer,
initialState: AppState(),
);

Once the store is created, you can use the StoreProvider widget to provide the store to the rest of the application. The StoreProvider widget takes the store and a child widget as arguments, and it makes the store available to the child widget and all its descendants.

4. Use the StoreProvider widget to provide the store to your application:

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StoreProvider<AppState>(
store: store,
child: MaterialApp(
title: 'Redux Example',
home: MyHomePage(),
),
);
}
}

In the child widget, you can use the StoreBuilder widget to access the state of the store. The StoreBuilder widget takes a builder function as an argument, which takes the store and returns a widget. The builder function is called whenever the state of the store changes, and it returns the updated UI.

5. Use the StoreBuilder widget to access the state of the store in a widget:

class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Redux Example'),
),
body: Center(
child: StoreBuilder<AppState>(
builder: (context, store) {
return Text(
'Counter: ${store.state.counter}',
style: TextStyle(fontSize: 24),
);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
store.dispatch(Actions.incrementCounter);
},
child: Icon(Icons.add),
),
);
}
}

This example demonstrates a basic integration of Redux in a Flutter app. The example shows how to create the store, provide it to the application, access the state of the store, and dispatch actions to update the state.

Note: This is just a basic example to get you started with Redux in Flutter. You can extend and customize it to fit your needs.

Conclusion:

Redux is a powerful state management library that can simplify the state management of a Flutter application. By using Redux, you can keep the state of your application in a single store, and you can manage the flow of data using actions and reducers. With its simple approach, Redux can help you build large and complex Flutter applications with ease.

❤ ❤ 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 Facebook, GitHub, Twitter, 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.