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?
2
Answers
Because
widget.subTitle
will get on runtime, instead of compile time. Another thing issubTitle
is final , notconst
.You can check What is the difference between the "const" and "final" keywords in Dart?
It is because
const Constructor
expectsconst 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:
Text
widget.tilte
aconst
variable.