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

Time:07-30

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

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"

CodePudding user response:

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 {...}
  • Related