Navigator 1.0 là API imperative: bạn tự push/pop từng màn lên stack. Navigator 2.0 (Router API) là declarative: stack màn hình được suy ra từ state của app, thường là URL. go_router là package của Flutter team bọc Router API cho dễ dùng, và là lựa chọn phổ biến cho dự án mới.
// Navigator 1.0
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => ProductPage(id: '12')),
);
// go_router: khai báo route theo URL
final router = GoRouter(routes: [
GoRoute(path: '/', builder: (_, __) => const HomePage()),
GoRoute(
path: '/product/:id',
builder: (_, state) => ProductPage(id: state.pathParameters['id']!),
),
]);
context.go('/product/12');Vì sao cần routing declarative:
- Deep link / URL trên web: mở /product/12 là dựng đúng stack, không phải tự parse.
- Redirect theo state: chưa đăng nhập thì redirect về /login ở một chỗ duy nhất.
- Nested navigation: StatefulShellRoute cho bottom navigation giữ stack riêng từng tab.
Navigator 1.0 vẫn ổn cho app nhỏ không cần deep link, và vẫn dùng song song được (dialog, bottom sheet).
Lưu ý: context.go() thay cả stack theo URL, còn context.push() đẩy thêm màn lên trên — nhầm hai hàm này làm nút back chạy sai. go_router hiện được Flutter team xếp vào trạng thái feature-complete (chỉ sửa lỗi, không thêm tính năng lớn); route type-safe cần thêm go_router_builder.