The Provider package helps you share data easily across your Flutter app. It makes your app organized and keeps your UI updated when data changes.
0
0
Provider package in Flutter
Introduction
You want to share user login info across many screens.
You need to update the UI when a counter or value changes.
You want to avoid passing data through many widget layers.
You want a simple way to manage app state without complex code.
Syntax
Flutter
ChangeNotifierProvider( create: (context) => YourModel(), child: YourWidget(), ) // To read data inside widgets: final model = Provider.of<YourModel>(context); // Or listen for changes: final model = context.watch<YourModel>();
ChangeNotifierProvider creates and provides a data model to widgets below it.
Use Provider.of or context.watch to access the data inside widgets.
Examples
Provides a
CounterModel to CounterWidget and its children.Flutter
ChangeNotifierProvider( create: (context) => CounterModel(), child: CounterWidget(), )
Reads the current count value from the provider and shows it in text.
Flutter
final counter = Provider.of<CounterModel>(context); Text('Count: ${counter.value}')
Listens for changes and calls
increment() to update the count.Flutter
final counter = context.watch<CounterModel>(); ElevatedButton( onPressed: () => counter.increment(), child: Text('Add'), )
Sample App
This app uses Provider to share a counter value. When you tap the button, the number updates automatically.
Flutter
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class CounterModel extends ChangeNotifier { int _count = 0; int get count => _count; void increment() { _count++; notifyListeners(); } } void main() { runApp( ChangeNotifierProvider( create: (context) => CounterModel(), child: const MyApp(), ), ); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Provider Example')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text('You have pushed the button this many times:'), Consumer<CounterModel>( builder: (context, counter, child) { return Text( '${counter.count}', style: const TextStyle(fontSize: 40), ); }, ), const SizedBox(height: 20), ElevatedButton( onPressed: () => context.read<CounterModel>().increment(), child: const Text('Increment'), ), ], ), ), ), ); } }
OutputSuccess
Important Notes
Always wrap your app or part of it with a Provider to share data.
Use notifyListeners() in your model to tell widgets to update.
Consumer widget helps rebuild only parts of UI that need updating.
Summary
Provider helps share and manage data easily in Flutter apps.
Use ChangeNotifierProvider with models that extend ChangeNotifier.
Widgets listen to data changes and update UI automatically.