skip to Main Content

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.

2

Answers


  1. 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?

    Login or Signup to reply.
  2. 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()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search