Search code examples
flutterflutter-layoutdart-null-safety

Flutter - 'the property 'settings' can't be unconditionally accessed because the receiver can be 'null''


The property 'settings' can't be unconditionally accessed because the receiver can be 'null',

what to do my code :

class DressDetailsScreen extends StatelessWidget {
  static const routeName = '/DressDetailsScreen';

  @override
  Widget build(BuildContext context) {
    final routeArgs = ModalRoute.of(context).settings.arguments ;
    return Scaffold(
      appBar: AppBar(
        title: Text('details'),
      ),
    );
  }
}`

this how it shows & my code


Solution

  • Just use

    final routeArgs = ModalRoute.of(context)!.settings.arguments;
    

    Since the inception of null safety in dart and the introduction of nullable types, you can't directly access a property of something that can be null.

    Here, you ModalRoute.of(context) could be a null value and that is why you need to use the bang operator (!) in order to access the settings from ModalRoute.of(context).

    What the bang operator does is that by using it after a nullable value, you are assuring dart that the value will definitely not be null.

    But obviously, this raises run time issues in case your value did actually turn out to be null, so use it with case.

    More on null safety