hermie_brown
hermie_brown

Reputation: 329

How do I pass an argument to a stateful widget when my widget uses string id to be referenced?

In my Flutter app, I'm using const String ids to navigate from screen to screen like so

  static const String id = 'onboarding5'; //in onboarding5.dart
  static const String id = 'Sessions';  //in sessions.dart

So in my main.dart, I initialized my routes like so

  routes { 
    Onboarding4.id: (context) => Onboarding4(),
    Onboarding5.id: (context) => Onboarding5(),
    Sessions.id: (context) => Sessions(),
  },

In my Onboarding5 screen, I have 2 buttons;

Clicking either will navigate user to SessionsScreen. My Sessions class extends stateful widget and uses an enum FormType to toggle view between SignUp and SignIn.

How do I pass the _formType argument from onboarding5 to the Sessions class constructor without changing my current way of routing through screens using static const String id?

Typically, the popular way without declaring a static const String id would have been like so

  Navigator.pushNamed(context, '/sessions');

or

  Navigator.pushNamed(context, Sessions());

Thanks in advance.

Upvotes: 0

Views: 1045

Answers (1)

Zeeshan Hussain
Zeeshan Hussain

Reputation: 842

You can pass your _formType as an argument. Create a class called 'SignArguments' which will contain your enum and other information which you might need to pass. You can receive the arguments in SessionsScreens using final ScreenArguments args = ModalRoute.of(context).settings.arguments;

enum sessionEnum {signUp , signIn}
class SignArguments {
  final sessionEnum sessionType;
  // you can pass other stuffs as well.
  SignArguments(this.sessionType);
}

Navigator.pushNamed(context, '/sessions',arguments:SignArguments(sessionEnum.signUp));

to receive your arguments

final ScreenArguments args = ModalRoute.of(context).settings.arguments;
// now you can access your enum which you have passed.
if (args.sessionType == sessionEnum.signIn) {
  // do something.
}

you can read more about arguments here https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments.

Upvotes: 1

Related Questions