0

Me encuentro realizando unas practicas con go_router y estoy intentando utilizar BottomNavigationWidget para navegar entre diferentes vistas pero me estoy encontrando con un problema y es que almomento de ejecutar la aplicacion en debug funciona medianamente bien, pero si utilizo la app descargada no navega hacia ningun lado, este es el main:

import 'package:flutter/material.dart';

import 'config/app_router.dart';

void main() {
  runApp(const App());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(useMaterial3: true),
      routerConfig: router,
    );
  }
}

Estas son mis rutas:

import 'package:bops_app_v3/screens/add_screen.dart';
import 'package:bops_app_v3/screens/home_screen.dart';
import 'package:bops_app_v3/screens/product_screen.dart';
import 'package:bops_app_v3/screens/profile_screen.dart';
import 'package:go_router/go_router.dart';

final router = GoRouter(routes: [
  GoRoute(
    path: '/',
    builder: (context, state) => const HomeScreen(),
  ),
  GoRoute(
    path: '/product',
    builder: (context, state) => const ProductScreen(),
  ),
  GoRoute(
    path: '/add',
    builder: (context, state) => const AddScreen(),
  ),
  GoRoute(
    path: '/profile',
    builder: (context, state) => const ProfileScreen(),
  ),
]);

Este es mi BottomNavigationWidget:

import 'package:bops_app_v3/config/app_router.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

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

  @override
  Widget build(BuildContext context) {
    return BottomNavigationBar(
      selectedItemColor: Colors.blue,
      unselectedItemColor: Colors.black,
      onTap: (index) {
        switch (index) {
          case 0:
            context.go('/');
            break;
          case 1:
            router.go('/product');
            break;
          case 2:
            context.go('/add');
            break;
          case 3:
            context.go('/profile');
            break;
        }
      },
      items: const [
        BottomNavigationBarItem(icon: Icon(Icons.home_outlined), label: 'Home'),
        BottomNavigationBarItem(
            icon: Icon(Icons.production_quantity_limits_outlined),
            label: 'Product'),
        BottomNavigationBarItem(icon: Icon(Icons.add_outlined), label: 'Add'),
        BottomNavigationBarItem(
            icon: Icon(Icons.person_2_outlined), label: 'Profile'),
      ],
    );
  }
}

Y estas son mis vistas, todas son iguales solo cambia el body:

import 'package:bops_app_v3/widget/botton_navegation_widget.dart';
import 'package:flutter/material.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: const Text('Home screen'),
      bottomNavigationBar: const BottomNavigationWidget(),
    );
  }
}

2 respuestas 2

0

Uso ShellRoute para ingresar las rutas que deben ir con la barra de navegacion. y ademas dos NavigatorKey para cada grupo de rutas, las que tienen bar y las que no.

Mira mi codigo puede que te sirva:

GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>();
GlobalKey<NavigatorState> shellNavigatorKey = GlobalKey<NavigatorState>();

var routesGo = GoRouter(
  debugLogDiagnostics: false,
  navigatorKey: rootNavigatorKey,
  observers: <NavigatorObserver>[FBAnalytics.observer],
  initialLocation: NamesRoutes.signIn,
  routes: <RouteBase>[
    ShellRoute(
      navigatorKey: shellNavigatorKey,
      builder: (context, state, child) {
        return ScaffoldWithNavBar(child: child);
      },
      routes: [
        GoRoute(
          parentNavigatorKey: shellNavigatorKey,
          name: NamesRoutes.home,
          path: NamesRoutes.home,
          pageBuilder: (context, state) => NoTransitionPage(
            child: PrincipalPage(),
          ),
        ),
        GoRoute(
          parentNavigatorKey: shellNavigatorKey,
          name: NamesRoutes.billing,
          path: NamesRoutes.billing,
          pageBuilder: (context, state) => NoTransitionPage(
            child: const BillingPage(),
          ),
        ),
        GoRoute(
          parentNavigatorKey: shellNavigatorKey,
          name: NamesRoutes.payPartialTax,
          path: NamesRoutes.payPartialTax,
          pageBuilder: (context, state) => NoTransitionPage(
            child: PayPartialTaxPage(),
          ),
        ),
        GoRoute(
          parentNavigatorKey: shellNavigatorKey,
          name: NamesRoutes.emitirFactura,
          path: NamesRoutes.emitirFactura,
          builder: (BuildContext context, GoRouterState state) {
            return const EmitirFacturaPage();
          },
        ),
      ],
    ),
    GoRoute(
      parentNavigatorKey: rootNavigatorKey,
      name: NamesRoutes.signIn,
      path: NamesRoutes.signIn,
      builder: (BuildContext context, GoRouterState state) {
        return SignInPage();
      },
    ),
    GoRoute(
      parentNavigatorKey: rootNavigatorKey,
      name: NamesRoutes.setNumber,
      path: NamesRoutes.setNumber,
      builder: (BuildContext context, GoRouterState state) {
        return SetNumberPage();
      },
    ),
    ....]

main.dart

  class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (context) => AuthBloc.instance,
        ),
        BlocProvider(
          create: (context) => HomeBloc.instance,
        ),
      ],
      child: ChangeNotifierProvider(
        create: (context) => AppLocale(),
        child: Consumer<AppLocale>(
          builder: (context, locale, child) {
            return MaterialApp.router(
              title: 'AppName',
              theme: AppTheme.light,
              locale: locale.locale,
              routerConfig: routesGo,
              debugShowCheckedModeBanner: false,
              supportedLocales: AppLocalizations.supportedLocales,
              localizationsDelegates: AppLocalizations.localizationsDelegates,
            );
          },
        ),
      ),
    );
  }
}

home_page.dart

import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';

class ScaffoldWithNavBar extends HookWidget {
  const ScaffoldWithNavBar({Key? key, required this.child}) : super(key: key);
  final Widget child;

  @override
  Widget build(BuildContext context) {

    return DefaultTabController(
      length: 3,
      child: Scaffold(
        extendBody: true,
        body: child,
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Padding(
          padding: const EdgeInsets.only(bottom: 5, left: 5, right: 5),
          child: FloatingActionButton(
            child: Icon(
              CustomIcons.emitirfc,
              color: ColorTheme.VioletaOscuro,
            ),
            elevation: 0,
            backgroundColor: ColorTheme.VerdePrimario,
            onPressed: () {
              routesGo.pushNamed(NamesRoutes.emitirFactura);
            },
          ),
        ),
        bottomNavigationBar: BottomNavigationBarCustom(),
      ),
    );
  }
}

class BottomNavigationBarCustom extends StatefulWidget {
  BottomNavigationBarCustom({
    Key? key,
  }) : super(key: key);

  @override
  State<BottomNavigationBarCustom> createState() =>
      _BottomNavigationBarCustomState();
}

class _BottomNavigationBarCustomState extends State<BottomNavigationBarCustom> {
  int _locationToTabIndex(String location) {
    final index =
        tabs.indexWhere((t) => location.startsWith(t.initialLocation));
    return index < 0 ? 0 : index;
  }

  int get _currentIndex => _locationToTabIndex(GoRouter.of(context).location);

  void _onItemTapped(BuildContext context, int tabIndex) {
    if (tabIndex != _currentIndex) {
      routesGo.push(tabs[tabIndex].initialLocation);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: ThemeData(
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
      ),
      child: BottomAppBar(
        notchMargin: 1,
        padding: EdgeInsets.only(bottom: 2),
        height: 70,
        clipBehavior: Clip.antiAlias,
        shape: CircularNotchedRectangle(),
        color: ColorTheme.VioletaPrimario,
        elevation: 0,
        child: BottomNavigationBar(
          currentIndex: _currentIndex,
          type: BottomNavigationBarType.fixed,
          unselectedItemColor: ColorTheme.white,
          fixedColor: ColorTheme.VerdePrimario,
          backgroundColor: Colors.transparent,
          onTap: (index) => _onItemTapped(context, index),
          items: tabs,
          selectedFontSize: 11,
          unselectedFontSize: 11,
        ),
      ),
    );
  }
}

class ScaffoldWithNavBarTabItem extends BottomNavigationBarItem {
  const ScaffoldWithNavBarTabItem(
      {required this.initialLocation, required Widget icon, String? label})
      : super(icon: icon, label: label);

  /// The initial location/path
  final String initialLocation;
}

List<ScaffoldWithNavBarTabItem> tabs = [
  ScaffoldWithNavBarTabItem(
    initialLocation: NamesRoutes.home,
    icon: Padding(
      padding: const EdgeInsets.only(top: 8, bottom: 2),
      child: Icon(
        CustomIcons.home,
        size: 26,
      ),
    ),
    label: "Home",
  ),
  ScaffoldWithNavBarTabItem(
    initialLocation: NamesRoutes.billing,
    icon: Padding(
      padding: const EdgeInsets.only(top: 8, bottom: 2),
      child: Icon(
        CustomIcons.facturacion,
        size: 26,
      ),
    ),
    label: "Facturación",
  ),
  ScaffoldWithNavBarTabItem(
    label: "Emitir Factura",
    icon: Padding(
      padding: const EdgeInsets.only(top: 14, bottom: 2),
      child: Text(""),
    ),
    initialLocation: NamesRoutes.emitirFactura,
  ),
  ScaffoldWithNavBarTabItem(
    initialLocation: NamesRoutes.payPartialTax,
    icon: Padding(
      padding: const EdgeInsets.only(top: 8, bottom: 2),
      child: Icon(
        CustomIcons.impuestos,
        size: 26,
      ),
    ),
    label: "Impuestos",
  ),
  ScaffoldWithNavBarTabItem(
    initialLocation: NamesRoutes.menu,
    icon: Padding(
      padding: EdgeInsets.only(top: 8, bottom: 2),
      child: Container(
        height: 26,
        child: Icon(
          CustomIcons.hamburguesa,
          size: 16,
        ),
      ),
    ),
    label: "Menu",
  ),
];
0

veo que algunos routes los llamas mediante tu router y otros mediante contexto.... estará allí el problema?

switch (index) {
          case 0:
            context.go('/');
            break;
          case 1:
            router.go('/product');
            break;
          case 2:
            context.go('/add');
            break;
          case 3:
            context.go('/profile');
            break;
        }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.