使用auto_route和flutter_bloc库导航页面不起作用

发布于 2025-02-13 19:31:01 字数 2968 浏览 0 评论 0原文

我尝试使用auto_route和flutter_bloc库来导航页面,但是没有触发bloclistener。

我正在使用print(SplashRoute == navigationState.initial()。uteType);用bloclistener检查触发条件,它是返回true

但是,bloclistener仍然没有触发。

应用程序的示例代码。谢谢。

代码问题:(?这是

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const AppWidget());
}


class AppWidget extends StatelessWidget {
  const AppWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final rootRouter = RootRouter();
    return MultiBlocProvider(
        providers: [
          BlocProvider(
            create: (_) => NavigationCubit()..nav(SplashRoute),
          ),
          // ... Other blocProvider
        ],
        child: BlocBuilder<ThemeCubit, ThemeState>(
          builder: (context, state) {
            return MaterialApp.router(
              debugShowCheckedModeBanner: false,
              theme: state.themeData,
              routerDelegate: rootRouter.delegate(),
              routeInformationParser: rootRouter.defaultRouteParser(),
            );
          },
        ));
  }
}

class SplashPage extends StatelessWidget {
  const SplashPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print(SplashRoute == NavigationState.initial().routeType);     // <------ return ture

    return MultiBlocListener(
      listeners: [
        BlocListener<NavigationCubit, NavigationState>(     // <------ Not working here
          listenWhen: (p, c) => c.routeType is SplashRoute,
          listener: (context, state) {
            LoggerService.simple.i('NavigationCubit page listening!!');
            context.read<NavigationCubit>().nav(HomeRoute);
            context.pushRoute(const HomeRoute());
          },
          // ... Other blocListener
        ),
      ],
      child: const Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      ),
    );
  }
}

我该如何解决我的

part of 'navigation_cubit.dart';

@freezed
abstract class NavigationState with _$NavigationState {
  const factory NavigationState({
    required Type routeType,
  }) = _NavigationState;

  factory NavigationState.initial() => const NavigationState(
        routeType:  SplashRoute,
      );
}

我的 >

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

import '../../../presentation/routes/router.gr.dart';

part 'navigation_cubit.freezed.dart';
part 'navigation_state.dart';

class NavigationCubit extends Cubit<NavigationState> {
  NavigationCubit() : super(NavigationState.initial());

  void nav(Type routeType) {
    emit(
      state.copyWith(
        routeType: routeType,
      ),
    );
  }

  @override
  Future<void> close() async {
    return super.close();
  }
}

I trying to using the auto_route and flutter_bloc libraries to navigate page, but BlocListener is not triggered.

I'm using print(SplashRoute == NavigationState.initial().routeType); to check the trigger condition with BlocListener, it's return true.

However, the BlocListener still not triggered.

How do I fix my code problem :(? This is the sample code of my app. Thanks.

main.dart

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const AppWidget());
}


class AppWidget extends StatelessWidget {
  const AppWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final rootRouter = RootRouter();
    return MultiBlocProvider(
        providers: [
          BlocProvider(
            create: (_) => NavigationCubit()..nav(SplashRoute),
          ),
          // ... Other blocProvider
        ],
        child: BlocBuilder<ThemeCubit, ThemeState>(
          builder: (context, state) {
            return MaterialApp.router(
              debugShowCheckedModeBanner: false,
              theme: state.themeData,
              routerDelegate: rootRouter.delegate(),
              routeInformationParser: rootRouter.defaultRouteParser(),
            );
          },
        ));
  }
}

class SplashPage extends StatelessWidget {
  const SplashPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print(SplashRoute == NavigationState.initial().routeType);     // <------ return ture

    return MultiBlocListener(
      listeners: [
        BlocListener<NavigationCubit, NavigationState>(     // <------ Not working here
          listenWhen: (p, c) => c.routeType is SplashRoute,
          listener: (context, state) {
            LoggerService.simple.i('NavigationCubit page listening!!');
            context.read<NavigationCubit>().nav(HomeRoute);
            context.pushRoute(const HomeRoute());
          },
          // ... Other blocListener
        ),
      ],
      child: const Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      ),
    );
  }
}

navigation_state.dart

part of 'navigation_cubit.dart';

@freezed
abstract class NavigationState with _$NavigationState {
  const factory NavigationState({
    required Type routeType,
  }) = _NavigationState;

  factory NavigationState.initial() => const NavigationState(
        routeType:  SplashRoute,
      );
}

navigation_cubit.dart

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

import '../../../presentation/routes/router.gr.dart';

part 'navigation_cubit.freezed.dart';
part 'navigation_state.dart';

class NavigationCubit extends Cubit<NavigationState> {
  NavigationCubit() : super(NavigationState.initial());

  void nav(Type routeType) {
    emit(
      state.copyWith(
        routeType: routeType,
      ),
    );
  }

  @override
  Future<void> close() async {
    return super.close();
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情仇皆在手 2025-02-20 19:31:01

我可以从您的代码中解释两件事。无论哪种方式,它都不会像您希望的那样工作。

我对您的问题的理解是,您正在尝试使用bloclistener在初始状态下导航,这是行不通的。

原因是bloclistener没有在初始状态下触发,因为它不是状态更改,而是由bloc定义的东西。

我看到的第二件事是,您在提供bloc时调用nav方法,这是一件好事:navigationCubit().. nav(splashroute)。但是,它将为参数RouteType设置相同的值,该值不会触发状态更改,因为它是相同的值。这意味着不会触发bloclistener

RouteType设置为最初的东西,也许将其设置为null,以便您的BLOC可以识别状态更改,然后将bloclistener触发。

编辑:

另外,c.RouteType是Splashroute似乎不正确。尝试更改为c.RouteType == splashroute中,请在属性时,否则您的函数在侦听器属性中都不会触发

There are two things I can interpret from your code. Either way it will not work as you had hoped.

My understanding from your question is that you are trying to navigate using the BlocListener on initial state, which doesn't work.

The reason is that BlocListener is not triggered on initial state as it is not a state change, but rather something that is defined by the bloc.

The second thing I see is that you call the nav method when providing the bloc, which is a good thing: NavigationCubit()..nav(SplashRoute). However, it will set the same value for the parameter routeType, which will not trigger a state change as it is the same value. Meaning that the BlocListener will not be triggered.

Set routeType to something else initially, perhaps set it to null, so that your bloc can identify a state change, then your BlocListener will be triggered.

EDIT:

Also, c.routeType is SplashRoute doesn't seem right. try changing to c.routeType == SplashRoute in your listenWhen property, otherwise your function in the listener property will not trigger

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文