skip to Main Content

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


  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?

    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search