Null Type Parameter Cannot be Assigned to String (NTPCAS)



AVAILABLE:    5

I cannot use questions[questionNumber] as a Text constructor in Flutter. Evaluating this constant expression raises an exception: dart(const_eval_throws_exception).

Error Message:
A value of type 'Null' can't be assigned to a parameter of type 'String' in a const constructor. Try using a subtype, or removing the keyword 'const'.
dartconst_constructor_param_type_mismatch

Explanation:
Arguments in a constant constructor must be constant expressions. Try making the argument a valid constant.

Code Snippet

Here is the code causing the issue:

class _QuizPageState extends State<QuizPage> {
  List<Widget> scoreKeeper = [];
  List<String> questions = [
    'You can lead a cow down stairs but not up stairs.',
    'Approximately one quarter of human bones are in the feet.',
    'A slug\'s blood is green.'
  ];

  int questionNumber = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const Expanded(
          flex: 5,
          child: Padding(
            padding: EdgeInsets.all(10.0),
            child: Center(
              child: Text(
                questions[questionNumber],
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 25.0,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

Solution

The error occurs because of the use of the const keyword for the Expanded widget. Removing the const keyword resolves the issue, as questions[questionNumber] is not a constant value.

The corrected code looks like this:

@override
Widget build(BuildContext context) {
  return Column(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: [
      Expanded(
        flex: 5,
        child: Padding(
          padding: EdgeInsets.all(10.0),
          child: Center(
            child: Text(
              questions[questionNumber],
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 25.0,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    ],
  );
}

By removing the const keyword, the widget becomes dynamic and can handle the runtime value of questions[questionNumber].


Post a Comment

Previous Next

نموذج الاتصال