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 Answers4

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;
Nidheesh MT
  • 1,074
  • 11
  • 18
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'
      });
    
      // ...
    }
    
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
1

just change

final Function onPress;

to

final Function() onPress;
q8yas
  • 897
  • 8
  • 10
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.

Andrija
  • 1,534
  • 3
  • 10