0

Example, I have a Wrap widget, and in children I have some code like:

           listTask.map((e) {
                  if (e.day!.contains(value))
                    return Padding(
                      padding: const EdgeInsets.all(4.0),
                      child: Container(
                        decoration: BoxDecoration(
                            shape: BoxShape.circle, color: Colors.black),
                        height: 20,
                        width: 20,
                      ),
                    );
                }).toList()

I want it return Padding whenever it pass if statement, but it get error The argument type 'List<Padding?>' can't be assigned to the parameter type 'List<Widget>'. How can I solve it? Thank you.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
Knighthuy
  • 3
  • 2

2 Answers2

0

The problem is that your callback to List.map does not explicitly return anything if the if condition fails, so the callback implicitly returns null, and you end up with a List<Padding?> instead of a List<Padding>. List.map creates a 1:1 mapping from input elements to output elements.

Either filter out the null elements afterward or use collection-for with collection-if:

  [for (var e in listTask)
    if (e.day!.contains(value))
      Padding(...),
  ]

Also see: How to convert a List<T?> to List in null safe Dart?

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
0

Try this :

listTask.map((e) {

                return (e.day!.contains(value)) ? Padding(
                  padding: const EdgeInsets.all(4.0),
                  child: Container(
                    decoration: BoxDecoration(
                        shape: BoxShape.circle, color: Colors.black),
                    height: 20,
                    width: 20,
                  ),
                ):Container();
            }).toList()
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 23 '23 at 15:59