这是我基于 Mickael 建议的实现:
首先我创建了一个 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:
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
}
}