Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

flutter : how to know whether argument is passed or not while navigator

here is my basic code for argument demo in flutter navigator

I have created this simple example to make my problem explain

here two button , one for add and other for edit

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

while clicking on add I am not passing argument
while clicking on edit I am passing string id ( like clicking on product and passing product id to next page)

while adding or editing I want to navigate same page

here my question is how to know argument is passed or not in next page

some suggested to pass argument while adding…but its not solution

I don’t want to pass any argument while add

here is basic code

class ProductPage extends StatelessWidget {

  static const routname='productpage';
  @override
  Widget build(BuildContext context) {
    final arg=ModalRoute.of(context)!.settings.arguments as String;
    return Scaffold(
      appBar: AppBar(title: Text('Product management sCreen'),),
      body: Text(arg!=null?'Edit Mode':'Add Mode'),
    );
  }
}
Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('HomeScreen'),),
      body: Center(child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
          TextButton(onPressed: (){
            Navigator.of(context).pushNamed(ProductPage.routname);
          }, child: Text('Add Product')),
          TextButton(onPressed: (){
            Navigator.of(context).pushNamed(ProductPage.routname,arguments: '1');
            }, child: Text('Edit Product')),

        ],),
      ),),
    );
  }

I am getting red screen while clicking on add
showing error

"null is not a subtype of type String"

>Solution :

Instead of using ! use ? to accept nullable data. If you are sure that you will get string or null use

 final String? arg=ModalRoute.of(context)?.settings.arguments as String?;

Now you can check

if (arg == null) {

} else {...}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading