What is Provider in Flutter: Simple Explanation and Example
Provider in Flutter is a package that helps manage and share app state easily across widgets. It acts like a bridge to pass data down the widget tree without manually passing it through constructors.How It Works
Imagine you have a family tree where parents pass down stories to their children. In Flutter, widgets are like family members, and Provider helps pass data or state from one widget to many others without repeating yourself.
Instead of giving data directly to each widget, Provider stores the data in one place and lets any widget listen to changes. When the data updates, all widgets that care about it get notified and update automatically.
This makes your app cleaner and easier to maintain because you don’t have to pass data through many layers of widgets manually.
Example
This example shows a simple counter app using Provider to share the counter value and update the UI when it changes.
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class Counter with ChangeNotifier { int _count = 0; int get count => _count; void increment() { _count++; notifyListeners(); } } void main() { runApp( ChangeNotifierProvider( create: (_) => Counter(), child: MyApp(), ), ); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Provider Example')), body: Center( child: Consumer<Counter>( builder: (context, counter, _) => Text('Count: ${counter.count}', style: TextStyle(fontSize: 30)), ), ), floatingActionButton: FloatingActionButton( onPressed: () => context.read<Counter>().increment(), child: Icon(Icons.add), ), ), ); } }
When to Use
Use Provider when you want to share data or state between many widgets without passing it down manually. It is great for:
- Managing app-wide settings like themes or user login status.
- Sharing data that changes over time, like counters, shopping carts, or form inputs.
- Keeping your code clean and easy to read by avoiding deeply nested constructor parameters.
It works well for small to medium apps and is often the first step before using more complex state management solutions.
Key Points
- Provider is a simple and efficient way to manage state in Flutter.
- It uses
ChangeNotifierto notify widgets about data changes. - Widgets listen to data changes using
Consumerorcontext.watch(). - It helps avoid passing data through many widget constructors.
- Provider is widely used and recommended for beginners and intermediate Flutter developers.