Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧭 What You’ll Learn
State is what makes your app dynamic and interactive.
In this chapter, you’ll learn:
🧠 What Is State?
In Flutter, state refers to any data that can change
over time. For example:
Flutter rebuilds widgets when the state they depend on
changes.
🎯 Types of State
Type |
Description |
Examples |
Ephemeral |
Local to a widget |
Toggle, TextField
input |
App state |
Shared across
multiple widgets/pages |
Authentication,
Cart, Theme |
🧪 Managing State with
setState()
setState() is the simplest way to manage state within a
StatefulWidget.
dart
class
CounterPage extends StatefulWidget {
@override
_CounterPageState createState() =>
_CounterPageState();
}
class
_CounterPageState extends State<CounterPage> {
int counter = 0;
void increment() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text('Count:
$counter')),
floatingActionButton: FloatingActionButton(
onPressed: increment,
child: Icon(Icons.add),
),
);
}
}
🔁 setState() triggers
build() to run again, updating the UI.
📋 Form State and Input
Handling
✅ Using TextEditingController
dart
final
TextEditingController nameController = TextEditingController();
TextField(
controller: nameController,
decoration: InputDecoration(labelText: 'Enter
your name'),
)
ElevatedButton(
onPressed: () {
print(nameController.text);
},
child: Text('Submit'),
)
🔐 Always dispose your
controllers:
dart
@override
void
dispose() {
nameController.dispose();
super.dispose();
}
🧩 Widget Lifecycle with
State
Method |
Purpose |
initState() |
Called when the widget
is first built |
build() |
Called every
time UI is updated |
dispose() |
Clean up resources
like controllers |
💼 Limitations of
setState()
🧠 Global State Management
For larger apps, use tools to manage global state. Popular
options include:
Package |
Pros |
Use Cases |
Provider |
Officially
recommended, simple |
User auth, theme,
shopping cart |
Riverpod |
Better than
Provider, safer |
Enterprise-level
apps |
Bloc |
Complex but powerful |
Event-driven state,
business logic |
GetX |
Lightweight,
reactive |
Quick apps,
minimal boilerplate |
📦 Using Provider –
Introduction
🔹 Step 1: Add to
pubspec.yaml
yaml
dependencies:
provider: ^6.0.0
🔹 Step 2: Create a
ChangeNotifier Class
dart
class
CounterModel extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
🔹 Step 3: Register
Provider
Wrap your app in ChangeNotifierProvider:
dart
void
main() {
runApp(
ChangeNotifierProvider(
create: (context) => CounterModel(),
child: MyApp(),
),
);
}
🔹 Step 4: Use Provider in
Widgets
dart
final
count = context.watch<CounterModel>().count;
ElevatedButton(
onPressed: () =>
context.read<CounterModel>().increment(),
child: Text('Count: $count'),
)
🧱 Provider Summary Table
Method |
Purpose |
ChangeNotifier |
Base class to manage
state |
notifyListeners() |
Notifies
widgets to rebuild |
context.read() |
Access provider
without rebuilding |
context.watch() |
Rebuild
widget when value changes |
🎯 Practical Use Case:
Login Form
dart
class
AuthModel extends ChangeNotifier {
String email = '';
String password = '';
bool isLoading = false;
void login() async {
isLoading = true;
notifyListeners();
await Future.delayed(Duration(seconds: 2));
isLoading = false;
notifyListeners();
}
}
Using AuthModel:
dart
TextField(
onChanged: (val) =>
context.read<AuthModel>().email = val,
)
ElevatedButton(
onPressed: () =>
context.read<AuthModel>().login(),
child:
context.watch<AuthModel>().isLoading ? CircularProgressIndicator() :
Text('Login'),
)
🧠 Choosing a State
Management Approach
App Size |
Recommended
Approach |
Small |
setState() |
Medium |
Provider,
Riverpod |
Large/Complex |
Bloc, Riverpod |
Rapid Dev |
GetX |
🧩 State Management Best
Practices
🔁 Comparison: setState()
vs Provider
Feature |
setState() |
Provider |
Scope |
Widget-local |
App-wide/global |
Complexity |
Low |
Moderate |
Reusability |
Limited |
High |
Testing |
Harder |
Easier |
Recommended for |
Small UIs |
Multi-screen apps |
✅ Summary
In this chapter, you’ve learned:
Answer:
Flutter is an open-source UI toolkit by Google that enables you to build
natively compiled apps for mobile, web, and desktop from a single codebase.
It’s fast, efficient, and perfect for building beautiful, responsive UIs with a
single programming language—Dart.
Answer:
Not necessarily. Dart is easy to learn, especially if you’re familiar with
JavaScript, Java, or C#. Most Flutter tutorials introduce Dart basics along the
way, making it beginner-friendly.
Answer:
Yes! Flutter allows you to develop apps for Android and iOS from a single
codebase. You can also compile apps for web, Windows, macOS, and Linux using
the same project.
Answer:
You’ll need a modern operating system like Windows 10+, macOS, or Linux, along
with tools like Git, an IDE (VS Code or Android Studio), and device emulators
or simulators for testing.
Answer:
Hot reload is a Flutter feature that allows you to instantly see code changes
in your running app without restarting the entire application. It boosts
productivity and speeds up the development process.
Answer:
You can download the Flutter SDK from flutter.dev, extract it to a folder, add it to your system
PATH, and run flutter doctor to check for setup issues. IDE plugins are also
available for Android Studio and VS Code.
Answer:
Yes, Flutter supports web development, though it’s still evolving compared to
mobile. It’s ideal for building highly interactive web apps or PWAs with
consistent UI and shared code.
Answer:
Widgets are the building blocks of a Flutter app. Everything you see on
screen—text, buttons, layout elements, animations—is a widget that can be
customized or nested inside other widgets.
Answer:
Both are popular cross-platform frameworks, but Flutter offers better
performance due to its native rendering engine and avoids using platform views.
React Native uses JavaScript and relies more on native components.
Answer:
Start with the official Flutter documentation, Flutter YouTube channel,
freeCodeCamp, and
community blogs on Medium or Dev.to. You can also explore interactive learning
on Flutter Apprentice.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)