1

I'm getting error "A value of type 'Null' can't be assigned to a parameter of type 'String' in a const constructor." from const Text().

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title, required this.subTitle});
  final String title;
  final String subTitle;
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
   return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.title,
          textAlign: TextAlign.center,
        ),
      ),
      body: Column(
        children: <Widget>[
          const Text(
            widget.subTitle,
          ),
      ),
    )
  }
} 

I already know I have to remove const to resolve the error. But Could anyone explain why does only const constructor have this error?

Minki Jung
  • 75
  • 1
  • 6
  • Are you certain that's the error you're getting? Is this your exact code? Using `const Text` there is not allowed, but the error shouldn't be saying anything about `Null` since `widget.subTitle` is non-nullable. – jamesdlin Mar 01 '23 at 17:16

2 Answers2

1

Because widget.subTitle will get on runtime, instead of compile time. Another thing is subTitle is final , not const.

You can check What is the difference between the "const" and "final" keywords in Dart?

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
1

It is because const Constructor expects const parameters or must be able to be evaluated as const at compilation time.

And you are trying to pass widget with a non-constant value .And this gives you error because they cannot be evaluated at compile time.

You have two possible solution:

  1. remove the const from the Text widget.
Text(widget.subTitle),

  1. make tilte a const variable.
const MyHomePage({..., required final const this.subTitle});
final const String subTitle;
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88