Milad-Akarie / auto_route_library

Flutter route generator
MIT License
1.59k stars 404 forks source link

Cannot Navigate To Nested Routes #1241

Closed rlee1990 closed 2 years ago

rlee1990 commented 2 years ago

Here is my router

@MaterialAutoRouter(
  replaceInRouteName: 'Page,Route',
  routes: <AutoRoute>[
    AutoRoute(
      page: TabbarViewScaffold,
      path: '/',
      guards: [AuthGuard],
      children: [
        AutoRoute(
          path: 'home',
          name: 'HomeRouter',
          page: Home,
          children: [
            // AutoRoute(
            //   page: Home,
            //   path: '',
            // ),
            // AutoRoute(
            //   path: 'post/:id',
            //   page:
            // ),
            AutoRoute(
              path: 'search',
              page: SearchPage,
            ),
            AutoRoute(
              path: 'profile/:id',
              name: 'ProfileRouter',
              page: ProfileView,
              children: [
                // AutoRoute(path: ':id', page: ProfileView),
                AutoRoute(
                  path: 'edit',
                  page: EditProfile,
                ),
              ],
            ),
          ],
        ),
        AutoRoute(
          path: 'messages',
          name: 'MessagesRouter',
          page: Chat,
          children: [
            // AutoRoute(
            //   path: '',
            //   page: Chat,
            // ),
          ],
        ),
        AutoRoute(
          path: 'notifications',
          name: 'NotificationsRouter',
          page: Notifications,
          children: [
            // AutoRoute(
            //   path: '',
            //   page: Notifications,
            // ),
          ],
        ),
        AutoRoute(
          path: 'livestreams',
          name: 'LivestreamsRouter',
          page: Livestreams,
          children: [
            // AutoRoute(
            //   path: '',
            //   page: Livestreams,
            // ),
          ],
        ),
      ],
    ),
    AutoRoute(
      path: '/create/post',
      page: CreatePost,
      guards: [AuthGuard],
    ),
    AutoRoute<bool>(page: Login, path: '/login'),
    AutoRoute(page: Signup, path: '/signup'),
  ],
)
class $SocialRouter {}

When I try to navigate to the search route I get this error

Looks like you're trying to navigate to a nested route without adding their parent to stack first
try navigating to TabbarViewScaffold -> HomeRouter -> SearchRoute

I have tried

AutoRouter.of(context)
                    .push(SearchRoute(userProfile: widget.userProfile));
context.navigateTo(HomeRouter(
                    userProfile: widget.userProfile,
                    children: [SearchRoute(userProfile: widget.userProfile)]));

Also tried with the tabbarviewrouter noting works. Using the context.navigate does not at all.

rlee1990 commented 2 years ago

When I tried with all 3 at once it will either reload the home page or do nothing. All while the path shows as: /home/search

jtdLab commented 2 years ago

To what did u set ur initial route?

Did u try something like

context.router.navigate(
  HomeRouter(
      userProfile: widget.userProfile,
      children: [SearchRoute(userProfile: widget.userProfile),
    ],
  ),
)
rlee1990 commented 2 years ago

To what did u set ur initial route?

Did u try something like

context.router.navigate(
  HomeRouter(
      userProfile: widget.userProfile,
      children: [SearchRoute(userProfile: widget.userProfile),
    ],
  ),
)

So I did not use plane navigate. I did navigateTo and home is my initial route for the sub route. WIth the tab route the apps inital route.

jtdLab commented 2 years ago

Can u share TabbarViewScaffold and HomeRouter?

rlee1990 commented 2 years ago

Tired doing that @jtdLab and noting happens

rlee1990 commented 2 years ago
 @override
  Widget build(BuildContext context) {
    log('Path: ${context.router.currentPath}');
    return LayoutBuilder(
      builder: (context, constraints) {
        if (constraints.maxWidth < 600) {
          //mobile portrait
          return Consumer(
            builder: (context, ref, _) {
              return ref.watch(userStream).when(
                    data: (data) {
                      return AutoTabsRouter(
                        routes: [
                          const HomeRouter(),
                          const MessagesRouter(),
                          const LivestreamsRouter(),
                          const NotificationsRouter(),
                        ],
                        builder: (context, child, animation) {
                          return Scaffold(
                            drawer: DrawerView(streamUserProfile: data!),
                            body: child,
                            extendBody: false,
                            key: _scaffoldKey,
                            bottomNavigationBar: CustomNavigationBar(
                              items: [
                                CustomNavigationBarItem(
                                  icon: const Icon(Icons.home_outlined),
                                  selectedIcon: const Icon(Icons.home_filled),
                                ),
                                CustomNavigationBarItem(
                                  selectedIcon: const Icon(Icons.chat_bubble),
                                  icon: const Icon(
                                      Icons.chat_bubble_outline_outlined),
                                ),
                                CustomNavigationBarItem(
                                  showBadge: false,
                                  badgeCount: 0,
                                  icon: const Icon(
                                      Icons.notifications_active_outlined),
                                  selectedIcon:
                                      const Icon(Icons.notifications_active),
                                ),
                                CustomNavigationBarItem(
                                  showBadge: false,
                                  badgeCount: 0,
                                  icon: const Icon(Icons.mic_outlined),
                                  selectedIcon: const Icon(Icons.mic),
                                ),
                                CustomNavigationBarItem(
                                    icon: const Icon(Icons.menu_outlined),
                                    selectedIcon: const Icon(Icons.menu)),
                              ],
                              selectedColor: Theme.of(context).primaryColor,
                              currentIndex: context.tabsRouter.activeIndex,
                              strokeColor: Theme.of(context).primaryColor,
                              backgroundColor: Theme.of(context).cardColor,
                              iconSize: 30,
                              blurEffect: false,
                              // borderRadius: const Radius.circular(25),
                              isFloating: false,
                              onTap: (index) {
                                if (index == 4) {
                                  _scaffoldKey.currentState!.openDrawer();
                                } else {
                                  context.tabsRouter.setActiveIndex(index);
                                }
                              },
                            ),
                          );
                        },
                      );
                    },
                    loading: () => const Scaffold(
                      body: Center(
                        child: CircularProgressIndicator(),
                      ),
                    ),
                    error: (error, stackTrace) => Center(
                      child: Text(error.toString()),
                    ),
                  );
            },
          );
        } else {
          //tablet && desktop portrait
          return const SizedBox.shrink();
        }
      },
    );
  }
}
rlee1990 commented 2 years ago
 @override
  Widget build(BuildContext context) {
    return ref.watch(userStream).when(
          data: (data) {
            return Scaffold(
              appBar: AppBar(
                title: Text(
                  AppLocalizations.of(context)!.appTitle.capitalizeFirstofEach,
                  style: const TextStyle(fontSize: 20),
                ),
                actions: [
                  IconButton(
                      icon: const Icon(FontAwesomeIcons.magnifyingGlass),
                      onPressed: () {
                        // AutoRouter.of(context)
                        //     .push(SearchRoute(userProfile: widget.userProfile));
                        // context.
                        context.router.navigate(HomeRouter(
                            // userProfile: data!,
                            children: [SearchRoute(userProfile: data!)]));
                      }),
                  PopupMenuButton(
                    icon: const Icon(Icons.add),
                    offset: const Offset(0.0, 50),
                    itemBuilder: (context) {
                      return [
                        PopupMenuItem(
                          // onTap: () async {
                          //   Future.delayed(
                          //       const Duration(seconds: 0),
                          //       () => widget.user.isVerified!
                          //           ? goLive()
                          //           : verifyPrompt());
                          // },
                          child: ListTile(
                            title: Text(AppLocalizations.of(context)!.goLive),
                            trailing: const Icon(
                              Icons.live_tv,
                              color: Colors.red,
                            ),
                          ),
                        ),
                        PopupMenuItem(
                          // onTap: () {
                          //   Future.delayed(
                          //       const Duration(seconds: 0), () => showStoryOptions());
                          // },
                          child: ListTile(
                            title: Text(AppLocalizations.of(context)!
                                .createStoryButton),
                            trailing: const Icon(
                              Icons.post_add_outlined,
                            ),
                          ),
                        ),
                        PopupMenuItem(
                          onTap: () {
                            context.router.push(CreatePost(userProfile: data!));
                          },
                          child: ListTile(
                            title: Text(
                                AppLocalizations.of(context)!.createPostButton),
                            trailing: const Icon(
                              FontAwesomeIcons.penToSquare,
                            ),
                          ),
                        ),
                      ];
                    },
                  ),
                ],
              ),
              body: LayoutBuilder(
                builder: (context, constraints) {
                  return Stack(
                    children: [
                      Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          // stories.isEmpty
                          //     ? const SizedBox.shrink()
                          //     : Container(
                          //         height: 125,
                          //         padding: const EdgeInsets.symmetric(
                          //             horizontal: 8, vertical: 8),
                          //         child: SmartRefresher(
                          //           controller: _storyRefreshController,
                          //           onRefresh: refreshStories,
                          //           onLoading: loadMoreStories,
                          //           child: ListView.builder(
                          //             scrollDirection: Axis.horizontal,
                          //             itemCount: stories.length,
                          //             shrinkWrap: true,
                          //             itemBuilder: (context, index) {
                          //               return Material(
                          //                 color: Colors.transparent,
                          //                 child: InkWell(
                          //                   onTap: () {
                          //                     if (stories[index].hasLiveStream!) {
                          //                       final item = stories[index]
                          //                           .stories!
                          //                           .firstWhere((element) =>
                          //                               element.isLiveStream == true);
                          //                       // TODO Review

                          //                       AutoRouter.of(context).push(
                          //                         LiveStreamAudienceRoute(
                          //                           uid: widget.user.agoraId!,
                          //                           activityId: item.id!,
                          //                           meetingId: item.meetingId!,
                          //                           meetingURL: item.hlsUrl!,
                          //                         ),
                          //                       );
                          //                     } else {
                          //                       AutoRouter.of(context).push(
                          //                         StoryViewScreenRoute(
                          //                           stories: stories,
                          //                           story: stories[index],
                          //                           updateState: updateViewedState,
                          //                         ),
                          //                       );
                          //                     }
                          //                   },
                          //                   child: Padding(
                          //                     padding: const EdgeInsets.symmetric(
                          //                         horizontal: 5.0),
                          //                     child: Column(
                          //                       mainAxisSize: MainAxisSize.min,
                          //                       crossAxisAlignment:
                          //                           CrossAxisAlignment.center,
                          //                       children: [
                          //                         SizedBox(
                          //                           height: 80,
                          //                           width: 80,
                          //                           child: Container(
                          //                             width: 75,
                          //                             height: 75,
                          //                             decoration: BoxDecoration(
                          //                               image: DecorationImage(
                          //                                   image:
                          //                                       CachedNetworkImageProvider(
                          //                                     stories[index].imageUrl !=
                          //                                             null
                          //                                         ? stories[index]
                          //                                             .imageUrl!
                          //                                         : SNAB.defaultImage,
                          //                                   ),
                          //                                   fit: BoxFit.cover),
                          //                               borderRadius:
                          //                                   BorderRadius.circular(70.0),
                          //                               border: Border.all(
                          //                                   color: stories[index]
                          //                                           .hasLiveStream!
                          //                                       ? Colors.red
                          //                                       : Theme.of(context)
                          //                                           .primaryColor,
                          //                                   width: stories[index].complete
                          //                                       ? 0
                          //                                       : 4),
                          //                             ),
                          //                           ),
                          //                         ),
                          //                         const SizedBox(
                          //                           height: 5,
                          //                         ),
                          //                         Text(
                          //                             stories[index].uid ==
                          //                                     widget.user.uid
                          //                                 ? AppLocalizations.of(context)!
                          //                                     .yourStory
                          //                                 : stories[index]
                          //                                     .name!
                          //                                     .capitalize(),
                          //                             maxLines: 1,
                          //                             overflow: TextOverflow.ellipsis),
                          //                       ],
                          //                     ),
                          //                   ),
                          //                 ),
                          //               );
                          //             },
                          //           ),
                          //         ),
                          //       ),
                          const SizedBox(
                            height: 8,
                          ),
                          posts.isEmpty
                              ? Center(
                                  child: Column(
                                    children: [
                                      SizedBox(
                                        height: constraints.maxHeight / 2,
                                        width: constraints.maxWidth,
                                        child: EmptyWidget(
                                          image: SocialJawn.nopost,
                                          title: AppLocalizations.of(context)!
                                              .emptyHomeTitle,
                                          subTitle:
                                              AppLocalizations.of(context)!
                                                  .emptyHomeSubTitle,
                                          hideBackgroundAnimation: true,
                                        ),
                                      ),
                                      ElevatedButton(
                                        style: ElevatedButton.styleFrom(
                                          elevation: 6,
                                        ),
                                        onPressed: () {
                                          refreshPost();
                                          // refreshStories();
                                        },
                                        child: Text(
                                            AppLocalizations.of(context)!
                                                .refreshButton),
                                      ),
                                    ],
                                  ),
                                )
                              : Expanded(
                                  child: SmartRefresher(
                                    controller: _postRefreshController,
                                    enablePullDown: true,
                                    enablePullUp: true,
                                    onLoading: loadMorePost,
                                    onRefresh: refreshPost,
                                    child: ListView.builder(
                                      shrinkWrap: true,
                                      controller: _postScrollController,
                                      physics:
                                          const AlwaysScrollableScrollPhysics(),
                                      itemCount: posts.length,
                                      itemBuilder: (context, index) {
                                        return PostWidget(
                                          index: index,
                                          removePin: () {},
                                          pinPost: () {},
                                          removePost: removeFromList,
                                          post: posts[index],
                                          userProfile: data!,
                                        );
                                      },
                                    ),
                                  ),
                                ),
                        ],
                      ),
                    ],
                  );
                },
              ),
            );
          },
          loading: () => const Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          ),
          error: (error, stackTrace) => Center(
            child: Text(error.toString()),
          ),
        );
  }
jtdLab commented 2 years ago

Every Route with children must return one of the auto_route specific widgets like AutoRouter or AutoTabsRouter (doc Nested Navigation / Tab Navigation) because its the root of a new subtree with its own navigation stack etc your Home widget does not have that u need to create something like a HomeRouter. To make it work i would remove the replaceInRouteName: 'Page,Route' because u might run into naming problems else.

HomeRouter then should be the parent of Home, Search, etc You need to apply this pattern to every nested Route for auto_route to work

You already did it correct in the TabbarViewScaffold (with Tabs)

class HomeRouter extends StatelessWidget {
  const HomeRouter({super.key});

  @override
  Widget build(BuildContext context) {
    return const AutoRouter();
  }
}
rlee1990 commented 2 years ago

@jtdLab thanks that makes sense. Ill give that a try.

rlee1990 commented 2 years ago

@jtdLab that worked thanks. Can't believe I missed that step.