A list "options" is generated from json file as below and no issue: For simplicity, some parts were removed
Future getidea(String subject) async {
List ideaList = [];
for (var idea in ideaListTemp) {
List options = [];
options.add(idea["A"]);
options.add(idea["B"]);
options.add(idea["C"]);
ideaList.add(ideaItem(
idea["ideaText"],
idea["ideaMedia"],
idea[options],
));
}
return (ideaList);
}
class ideaItem {
final String ideaText;
final String ideaMedia;
List? options;
ideaItem(
this.ideaText,
this.ideaMedia,
this.options,
);
}
However, when I use "options" to create a Widget, this error occur. error: The argument type 'List?' can't be assigned to the parameter type 'List'.
Widget build(BuildContext context) {
return Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(_horizontalMargin),
physics: const AlwaysScrollableScrollPhysics(),
child: Column(
children: [
_buildOptions(widget.fromJSON.options), // this will have the error message
],
),
),
);
}
Widget _buildOptions(List option) {
List<Widget> listElevatedButton = [];
for (var i = 0; i < option.length; i ) {
//print(allOptions[i]);
listElevatedButton.add(
Builder(
builder: (context) => Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () {
print('Use the update function');
},
child: Text(
option[i],
),
),
),
),
);
}
return Column(children: listElevatedButton);
}
What is the best practice to solve the issue?
CodePudding user response:
The variable options is being used carelessly, You need to make sure that the options
has value before using it, To do this you can put a null check like so:
_buildOptions(widget.fromJSON.options)
-> _buildOptions(widget.fromJSON.options ?? [])
This will give an empty list to _buildOptions
function as long as options
is empty and It won't build any widgets in _buildOptions
function.
I hope you understand the concept here.
CodePudding user response:
Your properties 'options' has type (optional) ?List, which mean it can contain List or null value. And you try use 'options' like argument in '_buildOptions' function, which need type List, not (optional) ?List.
Rewrite code like this:
Column(
children: [
_buildOptions(widget.fromJSON.options ?? []),
],
),
If the "widget.fromJSON.options" value is null, the _buildOptions will have the empty List, otherwise, it will have the value of the "widget.fromJSON.options" value.
Good luck ;)