provider design pattern #flutter
- Ilakk Manoharan
- Dec 5, 2022
- 2 min read
Updated: Jan 4, 2023
Explain the provider design pattern. Write a simple application in flutter using provider design pattern
The Provider pattern is a way to manage state in a Flutter application. It involves wrapping a piece of data in a provider object, which can then be accessed by any widget in the widget tree. This allows for easy access to shared data throughout the app, without having to pass data down through the widget hierarchy via constructor arguments or other means.
Here is an example of a simple Flutter application using the Provider pattern:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => Counter(),
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('You have pushed the button this many times:'),
Consumer<Counter>(
builder: (context, counter, child) {
return Text(counter.count.toString());
},
),
SizedBox(height: 20),
RaisedButton(
onPressed: () {
Provider.of<Counter>(context, listen: false).increment();
},
child: Text('Increment'),
),
],
),
),
),
);
}
}
class Counter with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
In this example, we have a Counter class that represents a simple counter. It has a single field, _count, which is a private field that stores the current count. The Counter class also has a public getter, count, which allows other widgets to access the current count.
The Counter class also has a method, increment, which increments the count by 1 and calls the notifyListeners method to trigger a rebuild of any widgets that depend on the Counter object.
We use the ChangeNotifierProvider widget at the root of the app to create an instance of the Counter class and make it available throughout the app.
In the MyApp widget, we use the Consumer widget to access the Counter object and display the current count. We also have a button that, when pressed, calls the increment method on the Counter object to increment the count.
This is a simple example of how the Provider pattern can be used in a Flutter application to manage state and make it easily accessible to different widgets throughout the app.
Comments