Home > Back-end >  Removing arguments from Route
Removing arguments from Route

Time:01-20

EDIT:

Thanks for the help, for anyone wondering how to add the checked solution to your main.dart. You need to add MultiProvider to your void main:

void main() {
  runApp(
    /// Providers are above [MyApp] instead of inside it, so that tests
    /// can use [MyApp] while mocking the providers
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => MyProvider()),
      ],
      child: MyApp(),
    ),
  );
}

I am fairly new to flutter and can't find anything on how to clear router arguments. My problem is quite simple, I get the user to scan a barcode and navigate back to the registration page. In the navigator I add the barcode as argument.

Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => RegistrationPage(),
      settings: RouteSettings(arguments: code),
   ),
);

Then I get the argument in the new page

 Widget build(BuildContext context) {
    String barcode = ModalRoute.of(context).settings.arguments;

    WidgetsBinding.instance.addPostFrameCallback((_){
      if (barcode != null && barcode != "") {
        _idInputControl.text = barcode;
        id = barcode;
        
        askForPersonalNr();
      }
    });
....

The "askForPersonalNr" function opens a dialog where the user has to enter his number, so we can connect it to the barcode id.

I leave the Dialog with "Navigator.of(context).pop();" after. This retriggers the widget build of my registration page (with the barcode still as an argument) and opens the dialog again. Resulting in an infinite loop.

I can't find anything online, does anybody know what I am doing wrong, or are arguments not intended for this purpose?

CodePudding user response:

This approach is a little bit risky, I'd do that with a provider. A simple provider for that would look like this:

class MyProvider extends ChangeNotifier {

  int barcode = 0;
  bool personalNumber = false;

//other methods and variables to store your info

}

Then you need to save the barcode value before the navigation...

...
final provider = Provider.of<MyProvider>(context);
provider.barcode = barcodeValue;
Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => RegistrationPage(),)
   ),
);
...

And finally modify the condition on your alertDialog:

Widget build(BuildContext context) {
    final provider = Provider.of<MyProvider>(context)
    WidgetsBinding.instance.addPostFrameCallback((_){
      if (provider.barcode != 0 && !provider.personalNumber) {
        //check this condition
        _idInputControl.text = barcode;
        id = barcode;
        
        askForPersonalNr();
      }
    });
....

Also, check at the official provider page how to implement it, you must initialize providers in your main. https://pub.dev/packages/provider

  • Related