Search code examples
flutterdartflutter-layoutdart-null-safety

when I try to use another class the problem show me that error: The argument type 'Null' can't be assigned to the parameter type 'Key'


class ColoredCircle extends StatelessWidget {

  ColoredCircle({required Key key, required this.color}) : super(key: key);

  final Color color;
  final double width = 50;

  @override
  Widget build(BuildContext context) {
    return Container(
        width: width ,
        height: width,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.red,
        )
    );
  }

Use case

ColoredCircle(color: Colors.red, key: null),

Solution

  • You can remove required from key on ColoredCircle and make it nullable

    class ColoredCircle extends StatelessWidget {
      const ColoredCircle({
        Key? key,
        required this.color,
      }) : super(key: key);
    

    Also you can do, by default StatelessWidget accept null data.

    class ColoredCircle extends StatelessWidget {
      const ColoredCircle({
        super.key,
        required this.color,
      });
    

    More about StatelessWidget