5

I am currently learning a course on Flutter. They provide you with an old stub project (nullable). When I try to migrate to Flutter 2.12.0 or higher - null safety kicks in. I have a basic understanding on how it works - but this I cannot find anywhere on Google or StackOverFlow.

I have a custom Card widget. It requires a Color parameter. Also I need it to be able to receive a Widget child parameter as well as an onPress Function, but I don't want to make them required. Please, help. How do I create a default value for Widgets and Functions?

class ReusableCard extends StatelessWidget {
  ReusableCard({@required this.cardColor, this.cardChild, this.onPress});
  final Color cardColor;
  final Widget cardChild;
  final Function onPress;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onPress,
      child: Container(
        child: cardChild,
        margin: EdgeInsets.all(10.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),
          color: cardColor,
        ),
      ),
    );
  }
}

4 Answers 4

3

You can make them nullable fields as follows

  ReusableCard({required this.cardColor, this.cardChild, this.onPress});
  final Color cardColor;
  final Widget? cardChild;
  final VoidCallback? onPress;
1
  • For nullable function, use ?

    class FooWidget extends StatelessWidget {
      final Function? onPressed; // <-- Nullable, use '?'
    
      FooWidget({
        this.onPressed,
      });
    
      // ... 
    }
    
  • For non-nullable function, use required

    class FooWidget extends StatelessWidget {
      final Function onPressed; // <-- Non-nullable
    
      FooWidget({
        required this.onPressed, // <-- Use 'required'
      });
    
      // ...
    }
    
1

just change

final Function onPress;

to

final Function() onPress;
0

I think this is what you need: https://dart.dev/null-safety/understanding-null-safety#late-variables.

You would define your variables as

late final Widget cardChild; 
late final Function onPress;

and then initialize them in your constructor (or initState for State objects) before using them.

1
  • Default value of an optional parameter must be constant May 18, 2021 at 6:52

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.