我想用固定的GoRouter和AppBar实现一个基于AppBar的导航,但是根据所选的路由动态地更改AppBar的标题。
我正在使用GoRouter的ShellRoute来拥有一个固定的Scaffold和AppBar,并且尝试用一个河边的Provider来更改标题
final titleProvider = StateProvider((ref) => 'Title');
ShellRoute(
builder: (BuildContext context, GoRouterState state, Widget child) {
return Scaffold(
body: child,
appBar: CustomAppBar()
);
},
routes: [
GoRoute(
path: DashboardScreenWeb.routeLocation,
name: DashboardScreenWeb.routeName,
builder: (context, state) {
ref.read(titleProvider.state).state = DashboardScreenWeb.title;
return const DashboardScreenWeb();
},
),
GoRoute(
path: BusinessDataScreen.routeLocation,
name: BusinessDataScreen.routeName,
builder: (context, state) {
ref.read(titleProvider.state).state = BusinessDataScreen.title;
return const BusinessDataScreen();
},
),
....我的CustomAppBar小部件像这样使用这个提供程序:
class CustomAppBar extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
var title = ref.watch(titleProvider);
return new AppBar(
title: Text(title!)
);
}
}但是,我得到了很多例外,很可能是因为我在错误的时间更改了提供者的状态。我能做些什么?
======== Exception caught by widgets library =======================================================
The following StateNotifierListenerError was thrown building Builder(dirty):
At least listener of the StateNotifier Instance of 'StateController<String>' threw an exception
when the notifier tried to update its state.
The exceptions thrown are:
setState() or markNeedsBuild() called during build.
This UncontrolledProviderScope widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was:
UncontrolledProviderScope
The widget which was currently being built when the offending call was made was:发布于 2022-11-05 10:40:17
您应该这样定义您的titleProvider:
final titleProvider = Provider<String>((ref) => 'Title');
并更新提供者:
GoRoute(
path: BusinessDataScreen.routeLocation,
name: BusinessDataScreen.routeName,
builder: (context, state) {
return ProviderScope(
overrides: [
titleProvider.overrideWithValue('youTitleHere')
]
child: const BusinessDataScreen(),
);
},
),
https://stackoverflow.com/questions/74326704
复制相似问题