Custom app bar in Flutter using the BLoC (Business Logic Components) pattern
To implement a custom AppBar with the BLoC (Business Logic Components) pattern in Flutter, you can follow these steps:
- First, define a BLoC class that implements the business logic and exposes a stream of data that the AppBar can listen to. For example, let’s say we want to create a BLoC that manages the title of the AppBar:
class TitleBloc {
final _controller = StreamController<String>();
Stream<String> get title => _controller.stream;
void setTitle(String newTitle) {
_controller.sink.add(newTitle);
}
void dispose() {
_controller.close();
}
}
2. Next, use a BLoC provider, such as the BlocProvider
widget from the flutter_bloc
package, to make the BLoC available to the widgets that need it. In this example, we will use a BlocProvider
at the root of the app to make the TitleBloc
available throughout the app:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => TitleBloc(),
child: MaterialApp(
// ...
),
);
}
}
3. In the AppBar, use a BlocBuilder
widget to listen to the data stream and rebuild the AppBar whenever the title changes. In this example, we will use a BlocBuilder
to display the title in the title
property of the AppBar
:
class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
final TitleBloc _titleBloc;
MyAppBar({Key key, @required TitleBloc titleBloc})
: _titleBloc = titleBloc,
super(key: key);
@override
Widget build(BuildContext context) {
return AppBar(
title: BlocBuilder<TitleBloc, String>(
bloc: _titleBloc,
builder: (context, title) {
return Text(title);
},
),
);
}
@override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
}
4. Use the custom AppBar in the Scaffold of your pages. In this example, we will use the MyAppBar
widget as the appBar
of the Scaffold
:
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final titleBloc = BlocProvider.of<TitleBloc>(context);
return Scaffold(
appBar: MyAppBar(titleBloc: titleBloc),
// ...
);
}
}
5. To update the title from other parts of the app, access the BLoC and call the setTitle
method.