Implementing Flutter Navigation & Routing

You can learn how to navigate from one screen to another screen in your flutter app in this article. You can check out flutter navigation sample at HERE.

Routing is one of the most important things and your app must have it to do handle multiple screens. A route is equal to an Activity in Android. A route is equal to a ViewController in iOS. A route is a widget in Flutter. In flutter navigation, You can navigate route using Navigator Widget. 

Create Dynamic Route Generator Class

We need to specify onGenerateRoute function in the root widget MaterialApp for Routing. So We create a standalone class route_generator.
 
import 'package:flutter/material.dart';
import 'package:flutternavigationsample/first_screen.dart';
import 'package:flutternavigationsample/second_screen.dart';

class RouteGenerator {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case '/FirstScreen':
        return MaterialPageRoute(builder: (_) => FirstScreen());
      case '/SecondScreen':
        return MaterialPageRoute(builder: (_) => SecondScreen());
      default:
      // If there is no such named route in the switch statement, e.g. /third
        return _errorRoute();
    }
  }

  static Route<dynamic> _errorRoute() {
    return MaterialPageRoute(builder: (_) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Error'),
        ),
        body: Center(
          child: Text('ERROR'),
        ),
      );
    });
  }
}
 
 

Integrate Route Generator in main.dart file

MaterialApp widget provides two parameters home and onGenerateRoute. Using home param, we can set widget which is displayed on launch of mobile application. We already created custom route generator class. Now we need to integrate it using onGenerateRoute parameter to handle navigation between all screens of flutter application.

import 'package:flutter/material.dart';
import 'package:flutternavigationsample/first_screen.dart';
import 'package:flutternavigationsample/route_generator.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FirstScreen(),
      onGenerateRoute: RouteGenerator.generateRoute,
    );
  }
}
 
 

Navigate From First Screen to Second Screen

Navigator.push() method is used to add a route to stack of routes managed by the navigator widget. Navigator.pushNamed() is an extension of Navigator.push() mehod. It is used to identify and differentiate between multiple routes. In this method, we give a name to routes. This method is specifically used when you have multiple routes in your flutter app.
 
Navigator.pushNamed(context, "/SecondScreen");
 
 

Pass Arguments With Routes

To pass arguments, We need to follow three steps.
 

(1) Set arguments in First Screen

List<String> playerNames = [“Cristiano Ronaldo, Lional Messi”];
Navigator.pushNamed(context, “/SecondScreen”, arguments: playerNames);
 

(2) Pass arguments in route_generator class

import 'package:flutter/material.dart';
import 'package:flutternavigationsample/first_screen.dart';
import 'package:flutternavigationsample/second_screen.dart';

class RouteGenerator {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    // Getting arguments passed in while calling Navigator.pushNamed
    final args = settings.arguments;

    switch (settings.name) {
      case '/FirstScreen':
        return MaterialPageRoute(builder: (_) => FirstScreen());
      case '/SecondScreen':
      // Validation of correct data type
        if (args is List<String>) {
          return MaterialPageRoute(
            builder: (_) => SecondScreen(
              listPlayerNames: args,
            ),
          );
        }
        // If args is not of the correct type, return an error page.
        // You can also throw an exception while in development.
        return _errorRoute();
      default:
      // If there is no such named route in the switch statement, e.g. /third
        return _errorRoute();
    }
  }

  static Route<dynamic> _errorRoute() {
    return MaterialPageRoute(builder: (_) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Error'),
        ),
        body: Center(
          child: Text('ERROR'),
        ),
      );
    });
  }
}
 

(3) Get arguments in Second Screen

List<String> listPlayerNames;
SecondScreen({this.listPlayerNames});
 
 

Return From Second screen to One Screen With Data

Make following changes in Second Screen

Navigator.pop(context,playerName);

Make following changes in First Screen

displayResult(BuildContext context, List<String> playerNames) async{
    final getSelectedPlayerName = await Navigator.pushNamed(context, “/SecondScreen”, arguments: playerNames);
    print(getSelectedPlayerName.toString());
}
 
 

Final First Screen & Second Screen

import 'dart:developer';

import 'package:flutter/material.dart';

class FirstScreen extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return FirstScreenState();
  }

}

class FirstScreenState extends State<FirstScreen>{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: (){
            List<String> playerNames = ["Cristiano Ronaldo", "Lional Messi"];
            displayResult(context,playerNames);
          },
          child: Text("Select Best Football Player"),
        ),
      ),
    );
  }

  displayResult(BuildContext context, List<String> playerNames) async{
    final getSelectedPlayerName = await Navigator.pushNamed(context, "/SecondScreen", arguments: playerNames);
    print(getSelectedPlayerName.toString());
  }

}
 
import 'package:flutter/material.dart';

class SecondScreen extends StatefulWidget{

  List<String> listPlayerNames;
  SecondScreen({this.listPlayerNames});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return SecondScreenState(listPlayerNames);
  }

}

class SecondScreenState extends State<SecondScreen>{

  List<String> listPlayerNames;
  SecondScreenState(this.listPlayerNames);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
           for(var playerName in listPlayerNames)
              Container(
                margin: EdgeInsets.only(top:15, bottom:15),
                child: RaisedButton(
                    onPressed: (){
                      Navigator.pop(context,playerName);
                    },
                    child : Text(playerName.toString())
                ),
              )
          ],
        ),
      )
    );
  }

}


 
 
flutter navigation
 
 
 
 

Leave a Reply