Karan Mehta
Karan Mehta

Reputation: 1541

Flutter - "setState() or markNeedsBuild() called during build" while selecting item from listview

I have created a list like this(outside build method):

final userTypes = ["Employee", "Candidate", "Visitor", "Staff"];

and also i have created a function to get selected list item like this(outside build method):

_onSelected(int index){
    setState(() {
      selectedIndex = index;
    });
  }

and i am using that function with listview builder like this(inside build method & scaffold):

ListView.builder(
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      itemCount: userTypes.length,
                      itemBuilder: (context, index) {
                        return Container(
                          color: selectedIndex != null && selectedIndex == index
                              ? Colors.red
                              : Colors.white,
                          margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
                          child: ListTile(
                            title: Text(userTypes[index],
                                style: TextStyle(
                                    fontSize: 20, color: Colors.white)),
                            onTap: _onSelected(index),
                          ),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(35)),
                              border: Border.all(
                                  color: Colors.white,
                                  width: 1,
                                  style: BorderStyle.solid)),
                        );
                      },
                    )

Upvotes: 0

Views: 124

Answers (1)

CopsOnRoad
CopsOnRoad

Reputation: 267404

You should use

onTap: () => _onSelected(index),

instead of

onTap: _onSelected(index),

Upvotes: 1

Related Questions