Setstate and Provider
Setstate and Provider
1. Using setState
We'll start with a simple counter app using setState to manage the state locally within a
widget.
Program:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
@override
return MaterialApp(
home: CounterScreen(),
);
@override
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
@override
return Scaffold(
body: Center(
child: Text(
'Counter: $_counter',
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
child: Icon(Icons.add),
),
);
2. Using Provider:
Next, let's refactor the code to use Provider for global state management. First, add
provider to your pubspec.yaml dependencies:
Program: yaml
dependencies:
flutter:
sdk: flutter
provider: ^6.0.5
Flutter project structure with the Counter model in its own file:
lib/
├── models/
└── screens/
step2: Then, create a new class for the Counter model, which will manage the state:
import 'package:flutter/material.dart';
int _count = 0;
void increment() {
_count++;
notifyListeners();
}
}
Step3: Now, update the main file to use Provider to wrap the app and manage state
globally:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
MultiProvider(
providers: [
],
child: MyApp(),
),
);
@override
return MaterialApp(
home: CounterScreen(),
);
}
class CounterScreen extends StatelessWidget {
@override
return Scaffold(
body: Center(
child: Text(
'Counter: ${counter.count}',
),
),
floatingActionButton: FloatingActionButton(
onPressed: counter.increment,
child: Icon(Icons.add),
),
);
Steps:
Explanation:
setState: In the first example, setState is used to update the _counter variable within the
widget, which rebuilds the widget to reflect the change.
Provider: In the second example, Provider manages the counter state outside of the
widget tree. The Counter class has an increment method that calls notifyListeners(),
informing all widgets using this state to rebuild when the count changes.
With this setup, Provider manages the state globally, which is helpful as your
app grows. This design allows other parts of the app to access and update the counter
without passing the state down through widget constructors.