Flutter
What is Provider?
Share state across the tree with Provider.
What is Provider?
Provider is a package that wraps InheritedWidget. It shares state from the top of the tree down to all children without passing it through every constructor. Each widget that needs the value gets it directly from the nearest provider above it.
import 'package:provider/provider.dart';
Children reach the provided value with Provider.of.
InheritedWidget and Provider.of
Provider is built on top of InheritedWidget. The Provider<T> widget supplies a value of type T; descendants read it with Provider.of<T>(context).
Provider<String>(
create: (_) => 'Hello',
child: Screen(),
)
final text = Provider.of<String>(context);
create is the function that produces the value.
Exercise Share a value with Provider
Provide the string 'Merhaba Provider' with Provider<String>. In Ekrani, read the value with Provider.of<String>(context). In main, call print('Provider hazır').
Show example solution
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
print('Provider hazır');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Provider<String>(
create: (_) => 'Merhaba Provider',
child: MaterialApp(
home: Ekrani(),
),
);
}
}
class Ekrani extends StatelessWidget {
@override
Widget build(BuildContext context) {
final yazi = Provider.of<String>(context);
return Scaffold(
body: Center(child: Text(yazi)),
);
}
}
Test yourself
-
What problem does the Provider package solve?
- The hassle of manually passing data through every constructor
- Reducing the APK size of the app
- Increasing hot reload speed
- Reducing Dart compile time
Show answer
The hassle of manually passing data through every constructor — Provider shares data in the tree instead of passing it down through constructors, solving the prop drilling problem.
-
Import the Provider package
import 'package:provider/____.dart';
Show answer
import 'package:provider/provider.dart';
-
Provider parts
- Provider
- Package wrapping InheritedWidget
- InheritedWidget
- Flutter widget that shares data in the tree
- create
- Function that produces the value
- Provider.of
- Method to read the provided value
Next lesson: ChangeNotifier