I am trying to build a class that I can call in my main code. This class is meant to take the user’s input, stored as a of String and, this is to be iterated through, and generate ‘Chip’ Widgets where each of the iterated String is passed into a ‘Chip’ constructor where the String becomes the title (or label).
When I try to return the widgetList, I get the following error:
Too many positional arguments: 0 expected, but 1 found.
Try removing the extra positional arguments, or specifying the name for named arguments.
class ChipSection extends StatelessWidget {
final List<String> userList;
const ChipSection({Key? key, required this.userList})
: super(key: key);
@override
Widget build(BuildContext context) {
List<Widget> widgetList = [];
for (int counter = 0; counter < userList.length; counter++) {
String word = userList[counter];
widgetList.add(Chip(
label: Text(word),
onDeleted: () {
print('I am deleted');
}));
}
;
return Container(widgetList);
}
}
What am I doing wrong and how should I recode this? Thank you!
3
Answers
For list you need to use a widget that use children instead of single child[widget]. For
Chip
,Wrap
widget is perfect.More about Wrap
In the
build
method you can only return one widget. If you want to return many chips, you must wrap them in another widget that receiveschildren
. You can use Column to align the chips vertically, Row to align horizontally, or Wrap to make them horizontally aligned with line breaking.I would write this widget as follow:
Click here to see a live demo.
See you! 🇧🇷
The error you are encountering indicates that you are passing an extra positional argument in your code, while the Container method does not take any positional argument.
In fact, in the last line of the build method, you are passing the list of created widgets directly as an argument to Container, while this method expects a value for its named parameter "child".
You can simply wrap the list of widgets in a Column widget, which will serve as a container for the list of widgets.
Or with Wrap widget :