Это моя реализация, основанная на предложении Микаэля:
Сначала я создал AppBarParams
класс для сохранения состояния AppBar.
@freezed
class AppBarParams with _$AppBarParams {
const factory AppBarParams({
required String title,
required List<Widget> actions,
}) = _AppBarParams;
}
Затем я создал StateProvider
в файле глобальных поставщиков, например:
final appBarParamsProvider = StateProvider<AppBarParams>((ref) {
return AppBarParams(title: "Default title", actions: []);
});
и прикрепил его к основному приложению с помощью Consumer
:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "App Title",
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SafeArea(
child: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(kToolbarHeight),
child: Consumer(
builder: (context, watch, child) {
final appBarParams = watch(appBarParamsProvider).state;
return AppBar(
title: Text(appBarParams.title),
actions: appBarParams.actions
);
})
),
body: ... your body widget
)
)
)
}
}
Затем вам просто нужно отредактировать состояние поставщика, чтобы обновить AppBar соответствующим образом, чтобы обновить AppBar, когда пользователь переключается между страницами, я создал этот миксин:
mixin AppBarHandler {
void updateAppBarParams(
BuildContext context, {
required String title,
List<Widget> Function()? actions
}) {
WidgetsBinding.instance!.addPostFrameCallback((_) async {
context.read(appBarParamsProvider).state = context
.read(appBarParamsProvider).state
.copyWith(
title: title,
actions: actions != null ? actions() : []
);
});
}
}
И на каждом главном экране, который должен изменить заголовок или действия, которые я сделал:
class Page1 extends HookWidget with AppBarHandler {
const Page1({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
updateAppBarParams(context,
title: "Page 1 title",
actions: () => [
IconButton(icon: const Icon(Icons.refresh), onPressed: () {
//a custom action for Page1
context.read(provider.notifier).updateEntries();
})
]
);
... your screen widget
}
}
person
MatPag
schedule
11.04.2021