I'm unable to use questions[questionNumber]
as a Text Constructor in Flutter.
Errors:
Evaluation of this constant expression throws an exception.dart(const_eval_throws_exception)
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
Arguments of a constant creation must be constant expressions. Try making the argument a valid constant, or use 'new' to call the constructor.dartconst_with_non_constant_argument
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,
),
),
),
),
),
],
);
}
}
The reason this happens is because with null safety enabled, your non-nullable parameter factor or key cannot be null . In the function and the constructor, these values might be null when the function is called without the named parameter: calculate() or Foo() .
When creating { question: 'How old are you?' , answer: null } try specify the precise type you want like <String, dynamic>{ question: 'How old are you?' , answer: null } .
In Dart, we use the late keyword to declare variables that will be initialized later. These are called non-nullable variables as they are initialized after the declaration. Hence, we use the late keyword. Note: Once we declare a non-nullable late variable, the variable can't be null at runtime.
The first way, assign the empty data with [] syntax. This creates an empty array list without elements. All the above are generic typed with dynamic values. The third way, If you want to create a typed empty number list, You have to assign with generic with int.
Well, the error is due to using the keyword const
for the Expanded
widget. Just remove it and you will be all good.
So 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,
),
),
),
),
),
],
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With