📱 18 / 100 Days Of Flutter, Kate's edition — go_router, Enums and Positioned

📱 18 / 100 Days Of Flutter, Kate's edition — go_router, Enums and Positioned

Hi, Flutter community and welcome to day 18 of my challenge đź‘‹

I continue watching Andrea's Flutter course and today I learned more about navigation in Flutter.

Navigator, Navigator 2.0 and go_router

This is how my dog feels about all of these:

routing.jpg

In my first Flutter exercises, I used simple imperative navigation also known as Navigator 1.0. This approach doesn't scale well if the app has many screens and requires “deep linking” or common web linking.

To solve those issues, the Flutter team developed Navigator 2.0 which is super flexible but also super complicated and verbose.

go_router takes Navigator 2.0 to the next level by hiding all its complexities and offering a clear coherent routing API. It reminded me of React Router and Express routes from the web world.

Everything I learned about go_router so far makes total sense. All routes are declared in a separate object. They can have different paths, names and other settings. Routes can be nested to maintain the correct "stack" when using the back button.

Performing navigation is super simple thanks to the build context extension:

// Replace current route with Home screen.
context.goNamed('home');

// Push orders screen on top of whatever is now at the top of the stack
context.pushNamed('orders');

Enums

It's a good idea to organise your constant strings (such as route names) in enums. Latest Dart introduced so-called enhanced enums but so far I used just basic ones:

enum AppRoute {
  home,
  product,
  orders,
}

Now instead of using the 'home' string in my router, I can use AppRoute.home.name.

Widget of the day - Positioned

Positioned is a simple widget that controls where a child of a Stack is positioned. Reminds me of position: absolute in CSS.

const Positioned(
            top: 20,
            right: 50,
            child: const Icon(Icons.shopping_cart)
),

There are also animated variations: AnimatedPositioned and PositionedTransition.

Summary

I didn't expect Flutter navigation to be so complex and sophisticated. Luckily, there is a great package go_router that provides a simple yet powerful routing solution on top of the low-level Flutter Router API.

Â