How to implement RouteAware in Flutter?

· 5 min read
How to implement RouteAware in Flutter?
How to implement RouteAware in Flutter?

In this article, we will see how to implement RouteAware In Flutter. Also, we will show how to use RouteAware to screen navigation in flutter app development.

How to implement RouteAware in Flutter?

RouteAware is an interface for objects that know about their present Route. This is utilized with RouteObserver to make a widget mindful of changes to the Navigator’s meeting history. RouteAware class will give you the following methods which you can expand:

  • > didPop(): In this method, when we pop the current screen, the didPop method is called.
  • > didPopNext():With this method, if you use RouteAware to extend the HomePage and open the SecondPage so that the HomePage is displayed, didPopNext is called. Therefore, this strategy is considered when the top screen is hidden and the current screen is displayed.
  • > didPush(): In this method, this is called when the current screen or route has been pushed into the navigation stack!
  • > didPushNext(): In this method, when we push SecondPage from HomePage, didPushNext is called. That is, this method is called when a new screen / root is moved from the current screen and the current screen disappears.

How to implement code in dart file:

First step is to make a variable of RouteObserver in main.dart.

final RouteObserver<ModalRoute> routeObserver = 
RouteObserver<ModalRoute>();

Inside your, MaterialApp you need to set navigatorObservers and pass our variable into it!. Then, our main. dart will look like this:

import 'package:flutter/material.dart';
import 'package:flutter_route_aware_demo/splash_screen.dart';

void main() => runApp(MyApp());
final RouteObserver<ModalRoute> routeObserver = RouteObserver<ModalRoute>();

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Splash(),
      navigatorObservers: [routeObserver],
    );
  }
}

Now after that you have to create a new dart file called home_page.dart inside the lib folder.

Now will be to extend RouteAware so that you can override the different methods! Also, you will have to subscribe to the route inside the initState() of HomePage.

@override
void initState() {
  WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
    routeObserver.subscribe(this, ModalRoute.of(context)!);
  });
  super.initState();
}

Override the methods: Add a column widget to the body. This widget adds an image and an ElevatedButton (). We are currently overwriting all available methods and clicking ElevatedButton () will take you to the next page.

import 'package:flutter/material.dart';
import 'package:flutter_route_aware_demo/second_page.dart';
import 'main.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with RouteAware {
  @override
  void didPush() {
    print('HomePage: Called didPush');
    super.didPush();
  }

  @override
  void didPop() {
    print('HomePage: Called didPop');
    super.didPop();
  }

  @override
  void didPopNext() {
    print('HomePage: Called didPopNext');
    super.didPopNext();
  }

  @override
  void didPushNext() {
    print('HomePage: Called didPushNext');
    super.didPushNext();
  }

  @override
  void initState() {
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      routeObserver.subscribe(this, ModalRoute.of(context)!);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.cyan,
        automaticallyImplyLeading: false,
        title: Text('Flutter RouteAware Demo'),
      ),
      body: Center(
        child:Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.asset("assets/logo.png",width: 300,),
              SizedBox(height: 
MediaQuery.of(context).size.height*0.25,),
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  textStyle: TextStyle(fontSize: 20),
                    minimumSize: Size.fromHeight(40),
                      primary: Colors.cyan,
                    ),
                    onPressed: () => Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (context) => SecondPage(),
                      ),
                    ),
                    child: Text("Home Page",)
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Create a new dart file named second_page.dart in the lib folder. You can do the same for second_page.dart. In the main part, add the text “Flutter Dev`s” and wrap it in the central widget. When you run your application, you should get the final console output similar to the following:

Launching lib/main.dart on ONEPLUS A5010 in debug mode...
Running Gradle task 'assembleDebug'...
✓ Built build/app/outputs/flutter-apk/app-debug.apk.
Installing build/app/outputs/flutter-apk/app.apk...
Debug service listening on ws://127.0.0.1:37333/8K4tNNeL45U=/ws
Syncing files to device ONEPLUS A5010...
I/flutter (19730): HomePage: Called didPush
I/flutter (19730): HomePage: Called didPushNext
I/flutter (19730): SecondPage: Called didPush
I/flutter (19730): HomePage: Called didPopNext
I/flutter (19730): SecondPage: Called didPop
I/flutter (19730): HomePage: Called didPushNext
I/flutter (19730): SecondPage: Called didPush
I/flutter (19730): HomePage: Called didPopNext
I/flutter (19730): SecondPage: Called didPop
I/flutter (19730): HomePage: Called didPushNext
I/flutter (19730): SecondPage: Called didPush
I/flutter (19730): HomePage: Called didPopNext
I/flutter (19730): SecondPage: Called didPop

Conclusion:

Thanks for being with us on a Flutter Journey!

So, in this article, we have seen how to Import Flutter Project in Android Studio. Also, feel free to comment and provide any other suggestions regarding Flutter.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. Also, the portal is full of cool resources from Flutter like Flutter Widget GuideFlutter Projects, Code libs and etc.

We are one of the most popular online portals dedicated to Flutter Technology. Daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply