BlocProvider
- Flutter course
- Intermediate
- Lesson 18/99
- 4 min
Provide Cubit to the tree with BlocProvider.
BlocProvider
BlocProvider provides a Cubit or Bloc to the widget tree. The create parameter takes the function that produces the Cubit instance.
BlocProvider<CounterCubit>(
create: (_) => CounterCubit(),
child: Screen(),
)The Cubit is automatically closed when it leaves the tree.
create and child
create is called when BlocProvider is first needed. child is the widget subtree under the provider.
BlocProvider<CounterCubit>(
create: (_) => CounterCubit(),
child: MaterialApp(home: Screen()),
)The Cubit's lifecycle is managed by the provider.
Practice Provide Cubit with BlocProvider
Provide the Cubit to the tree with BlocProvider<SayacCubit>. Create a new SayacCubit() instance with create. In main, call print('uygulama başladı').
Starter code
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SayacCubit extends Cubit<int> {
SayacCubit() : super(0);
}
void main() {
print('uygulama başladı');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// BlocProvider ile SayacCubit sağla
return MaterialApp(
home: Ekrani(),
);
}
}
class Ekrani extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text('ekran')));
}
}Sample solution
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SayacCubit extends Cubit<int> {
SayacCubit() : super(0);
}
void main() {
print('uygulama başladı');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider<SayacCubit>(
create: (_) => SayacCubit(),
child: MaterialApp(
home: Ekrani(),
),
);
}
}
class Ekrani extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text('ekran')));
}
}Expected output
uygulama başladı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is BlocProvider's create called?
- When the app closes
- On every build
- When BlocProvider is first needed Correct answer
- Only on error
Explanation: BlocProvider's create function is called when the provider is first needed, producing the Cubit instance.
2 Give BlocProvider the Cubit type
BlocProvider<____>(
create: (_) => SayacCubit(),
child: Ekrani(),
)
BlocProvider<SayacCubit>(
create: (_) => SayacCubit(),
child: Ekrani(),
)
Explanation: BlocProvider's type parameter is the Cubit class being provided; not SayacEvent or SayacState.
3 BlocProvider parts
| Term | Meaning |
|---|---|
BlocProvider |
Provides Cubit to the tree |
create |
Produces Cubit on first need |
child |
Widget subtree under provider |
close |
Called when Cubit is disposed |