In Flutter, the Provider
package is a dependency injection library that makes it easy to manage the state of your app and share it with other widgets. It works by wrapping a value (such as a piece of data or an object) in a Provider
widget, which can then be accessed by other widgets that are descendants of the Provider
in the widget tree.
Here is an example of how you could use the Provider
package to share a piece of data with multiple widgets:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => MyModel(),
child: MyApp(),
),
);
}
class MyModel with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final model = Provider.of<MyModel>(context);
return Scaffold(
body: Center(
child: Text(model.count.toString()),
),
floatingActionButton: FloatingActionButton(
onPressed: model.increment,
child: Icon(Icons.add),
),
);
}
}
In this example, the MyModel
class defines a count
property and a method to increment it. The MyModel
instance is wrapped in a ChangeNotifierProvider
widget and passed as the child of the MyApp
widget. The MyHomePage
widget can then access the count
property and the increment
method using the Provider.of
method. When the increment
method is called, it updates the count
property and triggers a rebuild of the MyHomePage
widget, causing the text in the center of the screen to update.