我想使用固定的Scaffold
和AppBar
实现基于GoRouter的导航,但要根据所选路线动态更改AppBar
的标题。
我使用GoRouter的ShellRoute
来修复Scaffold
和AppBar
,并尝试使用riverpod 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
widget使用此提供程序的方式如下:
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:
2条答案
按热度按时间aamkag611#
使用状态属性
state.location
并将title
传递给AppBar
Go工艺路线
自定义应用程序栏
输出:
ilmyapht2#
你应该像这样定义你的titleProvider:
并更新提供程序: