0

我想将主题更改为redTheme仅在我在特定路线上时。为此,我使用routingCallback

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'App',
      theme: defaultTheme(context),
      initialRoute: AppPages.INITIAL,
      getPages: AppPages.routes,
      routingCallback: (routing) => _routingCallback(context, routing),
    );
  }

  _routingCallback(BuildContext context, Routing routing) {
    if (routing.current == Routes.PURSUE_MODE) {
      _changeThemeIfNeeded(redTheme(context));
    } else {
      _changeThemeIfNeeded(defaultTheme(context));
    }
  }

  void _changeThemeIfNeeded(ThemeData theme) {
    Get.changeTheme(theme);
  }
}

不幸的是,它导致

════════ 小部件库捕获的异常═════════════════════════════␕════════════ ══════════════════ setState() 或 markNeedsBuild() 在构建期间调用。相关的导致错误的小部件是: Directionality file:///Users/jakub/.pub-cache/hosted/pub.dartlang.org/get_navigation-3.12.0/lib/src/root/root_widget.dart:235:22 ══════════════════════════════════════════════════ ══════════════════════════════════════════════════

正因为如此,我已经在 try-catch 块中包装了主题更改,所以一开始我没有遇到异常

  void _changeThemeIfNeeded(ThemeData theme) {
    try {
      if (Get.theme != theme) {
        Get.changeTheme(theme);
      }
    } catch (e) {
      print('Not ready e = $e');
    }
  }

Get但我相信使用框架有更优雅的方法来解决这个问题?

4

1 回答 1

2

我对 GetX 不是很熟悉。但是,为了避免setState() or markNeedsBuild() called during build.错误,您可以在您的情况下使用addPostFrameCallback,如下所示:

routingCallback: (routing) => WidgetsBinding.instance
      .addPostFrameCallback((_) => _routingCallback(context, routing)) 
于 2020-10-06T09:19:10.673 回答