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. We will see how to implement a demo program. 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 gives the accompanying methods which we can expand:

  • > didPop(): In this method, when we pop the current screen, the didPop method is called.
  • > didPopNext(): In this method, on the off chance that you have extended HomePage with RouteAware, and in case SecondPage is popped so HomePage is noticeable now, didPopNext is called. As such, this strategy is considered when the top screen is popped off and the current screen is apparent.
  • > 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. In other words, this method is called when a new screen/route is pushed from the current screen and the current screen is no longer visible.

How to implement code in dart file:

To start with, 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],
    );
  }
}

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, inside the initState() of HomePage, subscribe to the route.

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

Override the methods. In the body, we will add the Column widget. In this widget, we will add an image and ElevatedButton(). We are just overriding all the methods available and navigating to our next page onClick of our ElevatedButton().

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 called second_page.dart inside the lib folder. All same things can be done for the second_page.dart. In the body, we will add the text ”Flutter Dev’s” and wrap to it’s Center widget. When we run the application, we ought to get the console final output like the underneath.

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