I'm using MultiProvider in my home page on flutter app and work done.
But I have a custom App bar which contain a ChangeNotifierProvider with a consumer and not working. AppBar widget are not notify when notifyListener() function called.
home view:
/// Home screen.
class HomeScreen extends StatefulWidget {
/// Constructor
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final _homeViewModel = HomeViewModel();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const CustomAppBar(),
body: MultiProvider(
providers: [
ChangeNotifierProvider.value(value: _homeViewModel),
ChangeNotifierProxyProvider<HomeViewModel, SecondViewModel>(
create: (context) => SecondViewModel(),
update: (context, homeViewModel, secondViewModel) =>
secondViewModel!..load()),
],
child: Container()
}
}
app bar view:
/// Custom App Bar.
class CustomDropAppBar extends cs.AppBar {
/// Title.
final Widget? appBarTitle;
/// Constructor.
const CustomDropAppBar(
{Key? key,
this.appBarTitle,})
: super(key: key);
@override
State<CustomMenuAppBar> createState() => _CustomMenuAppBarState();
}
/// App bar state.
class _CustomMenuAppBarState extends State<CustomMenuAppBar> {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => CustomMenuViewModel(),
child: Consumer<CustomMenuViewModel>(
builder: (context, viewModel, child) => cs.AppBar(
title: widget.appBarTitle,
actions: [Container()])));
}
I think it's because I'm using MultiProvider in the body Scalford function? or it's because AppBar cannot containing consumer?
How I can fix this problem?
We cannot rebuild the AppBar(only) by wrapping it inside a Consumer. Rebuilding anything inside the AppBar requires rebuilding its parent Scaffold, or the whole build function. Use ChangeNotifierProvider for the HomeScreen and context.watch within the AppBar to listen for changes.