我想在运行时更改我的 flutter 应用程序主题,但遇到了一些问题。
问题是我正在使用 go router 进行导航,并且更改主题的选项位于第 4 个 shell 路由的设置页面上,我已使用流生成器包装了材质应用程序并提供了新主题,但它会重置应用程序并打开默认值当数据更改时路由主页,并重新启动以前在主页上发生的异步操作,我不希望用户留在设置页面上并查看设置页面本身的更改重置为默认值路线。
我认为的一个解决方案是使用带有主题数据的自定义继承小部件,而不使用材质应用程序提供的默认 Theme.of,但我不喜欢这种方法。
这可能是由于构建器内部定义了路由器配置,每次主题更改时都会更新。 Go router 可能因此每次都会重新启动。
要解决此问题,请在构建器方法之前定义路由器配置或在 ititState 中进行外部构建,如下所示:
class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
late RouterConfig<Object> _routerConfig;
@override
void initState() {
super.initState();
_routerConfig = GoRouter(
...
);
}
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Demo',
routerDelegate: _routerConfig.delegate(),
routeInformationParser: _routerConfig.defaultRouteParser(),
routerConfig: _routerConfig,
// routeInformationParser: _routerConfig.routeInformationParser,
// routeInformationProvider: _routerConfig.routeInformationProvider,
// routerDelegate: _routerConfig.routerDelegate,
);
}
}