Home > Mobile >  Flutter - How to pass optional Parameters to StatelessWidget?
Flutter - How to pass optional Parameters to StatelessWidget?

Time:09-19

2 variables mediumScreen and smallScreen must required But I wanna option.

FAIL

CodePudding user response:

in your pubspec.yaml file, change eenvironment sdk to:

sdk: ">=2.11.0 <3.0.0"

CodePudding user response:

Do this:

...
 Widget? mediumScreen; //Add a question mark after the dat type

CodePudding user response:

Check this :

class MyApp extends StatelessWidget {
  MyApp(this.yourData);

  final int yourData;
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'App Title',
      theme: new ThemeData(
        primarySwatch: Colors.green,
      ),
      home: new TestClass(yourData),
    );
  }
}

Another Class:

class TestClass extends StatelessWidget {
  TestClass(this.yourData);

  final int yourData;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Padding(
        padding: const EdgeInsets.only(left: 20.0, right: 20.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
          
          ],
        ),
      ),
    );
  }
}

CodePudding user response:

Because Flutter using null-safety your parameters must declare if it will be null or not.

as in dart documentation

With sound null safety variables are ‘non-nullable’ by default: They can be assigned only values of the declared type (e.g. int i=42), and never be assigned null. You can specify that a type of a variable is nullable (e.g. int? i), and only then can they contain either a null or a value of the defined type.

then in your case try giving it a default value:

class ResponsiveWidget extends StatelessWidget {
  final Widget largeScreen;
  final Widget mediumScreen;
  final Widget smallScreen;
  const ResponsiveWidget({
    Key? key,
    required this.largeScreen,
    this.mediumScreen = const SizedBox(), // changed
    this.smallScreen = const SizedBox(), // changed
  }) : super(key: key);
...

or you can say this will be null like:

class ResponsiveWidget extends StatelessWidget {
  final Widget largeScreen;
  final Widget? mediumScreen; // changed
  final Widget? smallScreen; // changed
  const ResponsiveWidget({
    Key? key,
    required this.largeScreen,
    this.mediumScreen,
    this.smallScreen,
  }) : super(key: key);
...
  • Related