Навигация — критическая часть любого Flutter приложения. В 2025 году есть два основных решения: go_router и AutoRoute. Разберём их особенности.
go_router
go_router от Google — это декларативный routing роутер.
Установка
dependencies:
go_router: ^14.0.0
Базовое использование
final router = GoRouter(
routes: [
GoRoute(
path: '/',
name: 'home',
builder: (context, state) => HomeScreen(),
),
GoRoute(
path: '/user/:id',
name: 'user',
builder: (context, state) {
final id = state.pathParameters['id'];
return UserScreen(id: id);
},
),
],
);
void main() => runApp(MaterialApp.router(routerConfig: router));
Deep linking
// Автоматически работает с URL
/material/app/:tab
// Программная навигация
context.go('/user/123');
// Named route
context.goNamed('user', params: {'id': '123'});
Guards
GoRoute(
path: '/profile',
redirect: (context, state) {
final user = FirebaseAuth.instance.currentUser;
if (user == null) {
return '/login';
}
return null;
},
builder: (context, state) => ProfileScreen(),
)
AutoRoute
AutoRoute — это code-first routing с генерацией кода.
Установка
dependencies:
auto_route: ^8.0.0
dev_dependencies:
auto_route_generator: ^8.0.0
build_runner: ^2.4.0
Аннотации
@RoutePage()
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) => Scaffold(...);
}
@RoutePage()
class UserScreen extends StatelessWidget {
const UserScreen({required this.id, super.key});
final String id;
@override
Widget build(BuildContext context) => Scaffold(...);
}
App router
@RouterConfig()
class AppRouter extends _$AppRouter {
@override
List<AutoRoute> get routes => [
AutoRoute(page: HomeRoute.page, initial: true),
AutoRoute(page: UserRoute.page),
];
}
Навигация
// Программная навигация
context.router.push(UserRoute(id: '123'));
// Back
context.router.pop();
// Replace
context.router.replace(UserRoute(id: '456'));
Guards
@RoutePage()
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key});
@override
Widget build(BuildContext context) => Scaffold(...);
}
// AutoRoute guard
class AuthGuard extends AutoRouteGuard {
@override
void onNavigation(NavigationResolver resolver, StackRouter router) {
final user = FirebaseAuth.instance.currentUser;
if (user == null) {
resolver.next(LoginRoute());
} else {
resolver.next();
}
}
}
Сравнение
| Характеристика | go_router | AutoRoute |
|---|---|---|
| Code generation | ❌ | ✅ |
| Type safety | Runtime | Compile-time |
| Deep linking | ✅ Из коробки | ✅ |
| Guards | ✅ Redirect | ✅ Guards |
| Nested routes | ✅ | ✅ |
| Learning curve | Низкая | Средняя |
| Ecosystem | Community |
Что выбрать?
go_router если: — Хотите решение от Google — Простая навигация — Не нужна code generation
AutoRoute если: — Нужна type safety — Сложная навигация — Хотите меньше boilerplate
Заключение
Оба решения отличные. Лично я рекомендую AutoRoute для больших проектов из-за type safety и compile-time проверок.