Search code examples
flutterdartdart-null-safety

Flutter Text Widget doesn't allow non nullable string param


This is a code that throws the error:

class DogName extends StatelessWidget {
  final String name;

  const DogName(this.name);

  @override
  Widget build(BuildContext context) {
    return const DecoratedBox(
      decoration: BoxDecoration(
          color: Colors.lightBlueAccent
      ),
      child: Padding(
        padding: EdgeInsets.all(8.0),
        child: Text(name),
      ),
    );
  }
}

and the error is the following

Error

Could you please, I'm just refresing my Flutter knowledge

thanks


Solution

  • To make nullable data use dataType?. Another issue is you are reading name on runtime, therefore DecoratedBox cant be const because of name variable.

    class DogName extends StatelessWidget {
      final String name;
    
      const DogName(this.name);
    
      @override
      Widget build(BuildContext context) {
        return DecoratedBox(
          decoration: BoxDecoration(
              color: Colors.lightBlueAccent
          ),
          child: Padding(
            padding: EdgeInsets.all(8.0),
            child: Text(name),
          ),
        );
      }
    }
    

    But it would be better if you use named constructor with key,

    class DogName extends StatelessWidget {
      final String name;
      const DogName({
        Key? key,
        required this.name,
      }) : super(key: key);
    
     
    
      @override
      Widget build(BuildContext context) {
        return DecoratedBox(
          decoration: BoxDecoration(color: Colors.lightBlueAccent),
          child: Padding(
            padding: EdgeInsets.all(8.0),
            child: Text(name),
          ),
        );
      }
    }
    

    Now if you want nullable, you need to provide default value means when name will get null.

    class DogName extends StatelessWidget {
      final String? name;
      const DogName({
        Key? key,
        this.name,
      }) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return DecoratedBox(
          decoration: BoxDecoration(color: Colors.lightBlueAccent),
          child: Padding(
            padding: EdgeInsets.all(8.0),
            child: Text(name ?? "default value"),
          ),
        );
      }
    }
    

    More about null-safety