Search code examples
flutterdartnavigator

Cannot find the 'arguments' in Navigator.pushNamed when pushing to next screen


I am trying to move signup screen to OTP screen. From Signup screen I need to pass email id to OTP screen. Now, I am using below, but cannot resolve the arguments: parameter in that.

Navigator.pushNamed(context, Routes.ROUTE_OTP,arguments:{"id": 'email'});

Searched so many tutorials they given there to use arguments:( but my bad I can't find:(


Solution

  • A simple example demonstrating your requirement follows:

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          onGenerateRoute: (settings) {
            WidgetBuilder builder;
            Map arguments = settings.arguments;
    
            switch (settings.name) {
              case '/':
                builder = (
                  BuildContext _,
                ) =>
                    SignUp();
                break;
              case '/otp':
                builder = (
                  BuildContext _,
                ) =>
                    Otp(id: arguments["id"]);
                break;
              default:
                return null;
            }
            return MaterialPageRoute(builder: builder, settings: settings);
          },
        );
      }
    }
    
    class SignUp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("Signup"),
          ),
          body: Center(
            child: FlatButton(
                onPressed: () {
                  Navigator.of(context).pushNamed(
                    "/otp",
                    arguments: {
                      "id": "email@email.com",
                    },
                  );
                },
                child: Text("SEND OTP")),
          ),
        );
      }
    }
    
    class Otp extends StatelessWidget {
      final String id;
    
      Otp({this.id});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("OTP"),
          ),
          body: Center(
            child: Text(id),
          ),
        );
      }
    }
    
    

    gif