SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
The Battle Between The
States (All About
Flutter Stateless &
Stateful Widgets, and
BLoC Architecture)
WWW.BACANCYTECHNOLOGY.COM
All things you come across in Flutter are
Widgets. Like Components/Controllers in
Ionic language, Activities in Android, or
React Native Components, everything you
create on your app screen is a Widget. So,
Buttons, Checkbox, Radio, ListView,
Drawer, Tabs, Grid, etc. that interact with
the visual aspect of your application are
widgets.
From this blog’s title, you would have made
out that there are two types of Widgets in
Flutter:Stateless & Stateful Widgets.
First, let us understand them:
Stateless Widgets do not have a specific
mutable state and are immutable, meaning
when the app is in action, the stateless
widgets cannot be redrawn. Hence, such
widgets do not have any internal state, and
you can modify their state only when they
are re-initialized.
Text, Column, Row, Container, etc. are
stateless widgets, and you need to pass
some parameters while creating these
widgets such as dimensions or decorations.
The state of such widgets remains the same
throughout the application lifetime.
[A bare minimum Stateless Widget]
On the contrary, Stateful Widgets have a
mutable state, and you can draw them n
number of times within their lifetime. Such
widgets are dynamic, and you can modify
their state without reinitiation.
Checkbox, Button, etc. are examples of
stateful widgets that generally contain an
inner value or data that determines their
state. The state of the widget may change as
a user selects an item of the checkbox or
presses a button.
[A bare minimum Stateful Widget]
You may also like to read;Top Flutter
Libraries, Tools, Packages and Plugins
State Change
Management
The state of a stateful widget can vary at
different stages during the app lifetime. On
every action, you need to define the state of
your stateful widget and reinitiate it. You
can execute the same by assigning
properties to the setState() method.
For a stateful widget, whenever you call this
function, it triggers the build() function of
the widget, which in turn redraws the
widget. Ideally, you should call the
setState() function under the onChanged
property of the widget.
Let us see a sample code where we imply
state change for a checkbox:
setState()
[Redrawing widget using setState()]
However, this method of widget redrawing
has some drawbacks. Before we get to the
issues, you need to understand the widget
hierarchy in your flutter application.
The following image will describe the
scenario well. Your application will be
categorized likewise. Now, for example, you
want to change the state of a child widget
when a parent widget is affected.
[Source: Blogspot]
In such scenarios, you will face the
following two major problems:
Widget Elementary Tree
Ideally, when you execute a setState()
function on a parent widget, it by-default
runs all its child widgets, whether or not
they are stateful widgets, or whether or not
they are stateful widgets need to be
redrawn.
[Source: Medium]
Issue #1 Parent to Child
Rendering
This way, all the child widgets are rendered
irrespective of a need to state-change. So,
you are unable to render a specific child
widget, keeping the rest unchanged.
Imagine you want to change the state of one
child widget when some action occurs on
another child widget. Both widgets are in
the same class and are rendered by one
parent widget. In such a case, you will be
unable to render a child widget from
another.
[Source: Medium]
Issue #2 Child to Child
Rendering
Now, to overcome these barriers of the
setState() method, and to enable MVC
architecture for your Flutter application,
there are some state management
techniques.
MobX, Scoped Model, Redux, and BLoC
Architecture can help you solve the issue.
However, Scoped Model and Redux again
face primary issues relevant to boilerPlate,
Scope, and data rendering.
So, let me share the most reliable state
management technique for the stateful
widgets of your Flutter app.
BLoC
Architecture
At their Google I/O conference (2018), Paolo
Soares and Cong Hui introduced the BLoC
architecture pattern for Business Logic
Component and applied it to the business
logic between various Dart applications.
Applying the BLoC architecture, you can
keep the business logic of your application
separate from the UI view by using Streams.
In this manner, it enables an MVVM
architecture for your app.
However, BLoC is a logic and not an
architectural theory, so you can choose any
suitable architecture for your application
and can still implement the BLoC logic.
[Source: https://www.raywenderlich.com]
For understanding the BLoC architecture,
you will first have to know some notions.
Streams yield multiple values that are
asynchronous events. Streams are similar to
the Future that the dart: async package
provides.
You can consider Sink as the end from
where you feed data in your application.
StreamController acts like the manager of
both Stream and Sink. It coordinates your
application functioning by handling the
business logic under it.
StreamBuilder is yet another manager that
observes StreamController and implements
the state change in your app.
Now, let us see how the BLoC architecture
works.
[Source: Medium]
The above diagram depicts a simple flow of
execution when a user interacts with your
application. When a user clicks a UI
component of your application, it sends an
event (action) to the BLoC component.
After that, the BLoC component interprets
the action and executes the required
business logic. It passes the state change of
the destination widget that will show the
results of his/her action.
Here, to understand the role of
InheritedWidget in the above figure, you
should read ahead.
Inherited Widget
To understand the concept of Inherited
Widgets, we will take an example, and for
that, you need to consider the following
widget-tree structure:
[Source: https://www.didierboelens.com]
Suppose Widget A is a button widget
(stateful) in our shopping cart example.
Widget B is a text box widget (stateful) that
changes state every time a user presses
Widget A (button). Widget Cis also a text
box widget (stateless), but that does not
need to change state on button press.
Here I have presented sample code for the
above-illustrated shopping cart example.
Whenever a user adds an item by clicking
on Widget A, the InheritedWidget
_MyInherited is recreated.
MyInheritedWidget contains a list of Items.
The static MyInheritedWidgetState
generates the state of the context
(BuildContext).
Every time the user adds an item in the cart,
the MyInheritedWidgetState rebuilds its
state.
This class builds a widget tree whose parent
is the MyInheritedWidget class.
WidgetA is a RaisedButton component that
invokes the addItem method of closest
MyInheritedWidget on user-press.
The number of items in the shopping cart
will be displayed in WidgetB, a simple text
component. It takes the updated value of
the cart-item from the closest
MyInheritedWidget.
In the above sample code, Widget A and
Widget B are rebuilt, and Widget C remains
unchanged as there is no need for it to
rebuild.
Google’s Flutter is an amazing language that
has proved its wonders. Whether Stateless
or Stateful Widgets, whatever type of app
you want to create for your users, you
would want the best of all Flutter app
development company. At Bacancy, we
have expert Flutter masters that can
accomplish almost anything that any other
language like Kotlin, Swift, or Java can
achieve.
Using the Flutter framework, our proficient
Flutter app developers can build next-
generation Android and iOS apps. Build
high-quality, native, and sophisticated
interfaces in no time with Flutter.
Take Away
Thank You

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Flutter presentation.pptx
Flutter presentation.pptxFlutter presentation.pptx
Flutter presentation.pptx
 
The magic of flutter
The magic of flutterThe magic of flutter
The magic of flutter
 
React workshop
React workshopReact workshop
React workshop
 
Angular
AngularAngular
Angular
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
 
Javascript
JavascriptJavascript
Javascript
 
Dart presentation
Dart presentationDart presentation
Dart presentation
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
導入 Flutter 前你應該知道的事
導入 Flutter 前你應該知道的事導入 Flutter 前你應該知道的事
導入 Flutter 前你應該知道的事
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
C・C++用のコードカバレッジツールを自作してみた話
C・C++用のコードカバレッジツールを自作してみた話C・C++用のコードカバレッジツールを自作してみた話
C・C++用のコードカバレッジツールを自作してみた話
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
Chapter 2 Flutter Basics Lecture 1.pptx
Chapter 2 Flutter Basics Lecture 1.pptxChapter 2 Flutter Basics Lecture 1.pptx
Chapter 2 Flutter Basics Lecture 1.pptx
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Flutter Festivals GDSC ASEB | Introduction to Dart
Flutter Festivals GDSC ASEB | Introduction to DartFlutter Festivals GDSC ASEB | Introduction to Dart
Flutter Festivals GDSC ASEB | Introduction to Dart
 
What is flutter and why should i care?
What is flutter and why should i care?What is flutter and why should i care?
What is flutter and why should i care?
 
React redux-tutoriel-1
React redux-tutoriel-1React redux-tutoriel-1
React redux-tutoriel-1
 
Angular Routing Guard
Angular Routing GuardAngular Routing Guard
Angular Routing Guard
 
Styled components presentation
Styled components presentationStyled components presentation
Styled components presentation
 
Telephony API
Telephony APITelephony API
Telephony API
 

Ähnlich wie The battle between the states (all about flutter stateless & stateful widgets, and BLoC architecture)

FlutterArchitecture FlutterArchitecture.ppt
FlutterArchitecture FlutterArchitecture.pptFlutterArchitecture FlutterArchitecture.ppt
FlutterArchitecture FlutterArchitecture.ppt
KevinNemo
 
View groups containers
View groups containersView groups containers
View groups containers
Mani Selvaraj
 

Ähnlich wie The battle between the states (all about flutter stateless & stateful widgets, and BLoC architecture) (20)

Mobile Application Development class 006
Mobile Application Development class 006Mobile Application Development class 006
Mobile Application Development class 006
 
Flutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdfFlutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdf
 
Rc085 010d-vaadin7
Rc085 010d-vaadin7Rc085 010d-vaadin7
Rc085 010d-vaadin7
 
FlutterArchitecture FlutterArchitecture.ppt
FlutterArchitecture FlutterArchitecture.pptFlutterArchitecture FlutterArchitecture.ppt
FlutterArchitecture FlutterArchitecture.ppt
 
View groups containers
View groups containersView groups containers
View groups containers
 
REACT pdf.docx
REACT pdf.docxREACT pdf.docx
REACT pdf.docx
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
Mobile Application Development class 003
Mobile Application Development class 003Mobile Application Development class 003
Mobile Application Development class 003
 
Developer Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for BeginnersDeveloper Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for Beginners
 
iOS Development (Part 2)
iOS Development (Part 2)iOS Development (Part 2)
iOS Development (Part 2)
 
Hello Android
Hello AndroidHello Android
Hello Android
 
Mca 504 dotnet_unit5
Mca 504 dotnet_unit5Mca 504 dotnet_unit5
Mca 504 dotnet_unit5
 
GWT training session 2
GWT training session 2GWT training session 2
GWT training session 2
 
Knockout in action
Knockout in actionKnockout in action
Knockout in action
 
Redux State Management System A Comprehensive Review
Redux State Management System A Comprehensive ReviewRedux State Management System A Comprehensive Review
Redux State Management System A Comprehensive Review
 
Metamorphosis from Forms to Java: A technical lead's perspective, part II
Metamorphosis from Forms to Java:  A technical lead's perspective, part IIMetamorphosis from Forms to Java:  A technical lead's perspective, part II
Metamorphosis from Forms to Java: A technical lead's perspective, part II
 
Force Flutter to Rebuild or Redraw All Widgets.pptx
Force Flutter to Rebuild or Redraw All Widgets.pptxForce Flutter to Rebuild or Redraw All Widgets.pptx
Force Flutter to Rebuild or Redraw All Widgets.pptx
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
 
Build UI of the Future with React 360
Build UI of the Future with React 360Build UI of the Future with React 360
Build UI of the Future with React 360
 
Flutter-Festivals Day-2.pptx
Flutter-Festivals Day-2.pptxFlutter-Festivals Day-2.pptx
Flutter-Festivals Day-2.pptx
 

Mehr von Katy Slemon

Mehr von Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Kürzlich hochgeladen (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

The battle between the states (all about flutter stateless & stateful widgets, and BLoC architecture)

  • 1. The Battle Between The States (All About Flutter Stateless & Stateful Widgets, and BLoC Architecture) WWW.BACANCYTECHNOLOGY.COM
  • 2. All things you come across in Flutter are Widgets. Like Components/Controllers in Ionic language, Activities in Android, or React Native Components, everything you create on your app screen is a Widget. So, Buttons, Checkbox, Radio, ListView, Drawer, Tabs, Grid, etc. that interact with the visual aspect of your application are widgets. From this blog’s title, you would have made out that there are two types of Widgets in Flutter:Stateless & Stateful Widgets. First, let us understand them:
  • 3. Stateless Widgets do not have a specific mutable state and are immutable, meaning when the app is in action, the stateless widgets cannot be redrawn. Hence, such widgets do not have any internal state, and you can modify their state only when they are re-initialized. Text, Column, Row, Container, etc. are stateless widgets, and you need to pass some parameters while creating these widgets such as dimensions or decorations. The state of such widgets remains the same throughout the application lifetime.
  • 4. [A bare minimum Stateless Widget] On the contrary, Stateful Widgets have a mutable state, and you can draw them n number of times within their lifetime. Such widgets are dynamic, and you can modify their state without reinitiation. Checkbox, Button, etc. are examples of stateful widgets that generally contain an inner value or data that determines their state. The state of the widget may change as a user selects an item of the checkbox or presses a button.
  • 5. [A bare minimum Stateful Widget] You may also like to read;Top Flutter Libraries, Tools, Packages and Plugins
  • 7. The state of a stateful widget can vary at different stages during the app lifetime. On every action, you need to define the state of your stateful widget and reinitiate it. You can execute the same by assigning properties to the setState() method. For a stateful widget, whenever you call this function, it triggers the build() function of the widget, which in turn redraws the widget. Ideally, you should call the setState() function under the onChanged property of the widget. Let us see a sample code where we imply state change for a checkbox: setState()
  • 8. [Redrawing widget using setState()] However, this method of widget redrawing has some drawbacks. Before we get to the issues, you need to understand the widget hierarchy in your flutter application.
  • 9. The following image will describe the scenario well. Your application will be categorized likewise. Now, for example, you want to change the state of a child widget when a parent widget is affected. [Source: Blogspot] In such scenarios, you will face the following two major problems: Widget Elementary Tree
  • 10. Ideally, when you execute a setState() function on a parent widget, it by-default runs all its child widgets, whether or not they are stateful widgets, or whether or not they are stateful widgets need to be redrawn. [Source: Medium] Issue #1 Parent to Child Rendering
  • 11. This way, all the child widgets are rendered irrespective of a need to state-change. So, you are unable to render a specific child widget, keeping the rest unchanged.
  • 12. Imagine you want to change the state of one child widget when some action occurs on another child widget. Both widgets are in the same class and are rendered by one parent widget. In such a case, you will be unable to render a child widget from another. [Source: Medium] Issue #2 Child to Child Rendering
  • 13. Now, to overcome these barriers of the setState() method, and to enable MVC architecture for your Flutter application, there are some state management techniques. MobX, Scoped Model, Redux, and BLoC Architecture can help you solve the issue. However, Scoped Model and Redux again face primary issues relevant to boilerPlate, Scope, and data rendering. So, let me share the most reliable state management technique for the stateful widgets of your Flutter app.
  • 15. At their Google I/O conference (2018), Paolo Soares and Cong Hui introduced the BLoC architecture pattern for Business Logic Component and applied it to the business logic between various Dart applications. Applying the BLoC architecture, you can keep the business logic of your application separate from the UI view by using Streams. In this manner, it enables an MVVM architecture for your app. However, BLoC is a logic and not an architectural theory, so you can choose any suitable architecture for your application and can still implement the BLoC logic.
  • 16. [Source: https://www.raywenderlich.com] For understanding the BLoC architecture, you will first have to know some notions. Streams yield multiple values that are asynchronous events. Streams are similar to the Future that the dart: async package provides.
  • 17. You can consider Sink as the end from where you feed data in your application. StreamController acts like the manager of both Stream and Sink. It coordinates your application functioning by handling the business logic under it. StreamBuilder is yet another manager that observes StreamController and implements the state change in your app. Now, let us see how the BLoC architecture works.
  • 18. [Source: Medium] The above diagram depicts a simple flow of execution when a user interacts with your application. When a user clicks a UI component of your application, it sends an event (action) to the BLoC component.
  • 19. After that, the BLoC component interprets the action and executes the required business logic. It passes the state change of the destination widget that will show the results of his/her action. Here, to understand the role of InheritedWidget in the above figure, you should read ahead. Inherited Widget To understand the concept of Inherited Widgets, we will take an example, and for that, you need to consider the following widget-tree structure:
  • 20. [Source: https://www.didierboelens.com] Suppose Widget A is a button widget (stateful) in our shopping cart example. Widget B is a text box widget (stateful) that changes state every time a user presses Widget A (button). Widget Cis also a text box widget (stateless), but that does not need to change state on button press.
  • 21. Here I have presented sample code for the above-illustrated shopping cart example. Whenever a user adds an item by clicking on Widget A, the InheritedWidget _MyInherited is recreated.
  • 22. MyInheritedWidget contains a list of Items. The static MyInheritedWidgetState generates the state of the context (BuildContext).
  • 23. Every time the user adds an item in the cart, the MyInheritedWidgetState rebuilds its state. This class builds a widget tree whose parent is the MyInheritedWidget class.
  • 24. WidgetA is a RaisedButton component that invokes the addItem method of closest MyInheritedWidget on user-press.
  • 25. The number of items in the shopping cart will be displayed in WidgetB, a simple text component. It takes the updated value of the cart-item from the closest MyInheritedWidget. In the above sample code, Widget A and Widget B are rebuilt, and Widget C remains unchanged as there is no need for it to rebuild.
  • 26. Google’s Flutter is an amazing language that has proved its wonders. Whether Stateless or Stateful Widgets, whatever type of app you want to create for your users, you would want the best of all Flutter app development company. At Bacancy, we have expert Flutter masters that can accomplish almost anything that any other language like Kotlin, Swift, or Java can achieve. Using the Flutter framework, our proficient Flutter app developers can build next- generation Android and iOS apps. Build high-quality, native, and sophisticated interfaces in no time with Flutter. Take Away