I am trying to call setState
inside a ListView.builder
which itself is inside a FutureBuilder
FutureBuilder<List<dynamic>>(
future: BidRepository().bidsTrucker('new'),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
final trips = snapshot.data!;
return ListView.builder(
itemCount: trips.length,
itemBuilder: ((context, index) {
final trip = trips[index];
return AcceptBidCard(
fromLocation:
'${trip['from_address']['name']}, ${trip['from_address']['country']}',
toLocation:
'${trip['to_address']['name']}, ${trip['to_address']['country']}',
bidderName: trip['customer_name'],
date: DateFormat('dd-MM-yyyy')
.format(DateTime.parse(trip['trip_date'])),
tripId: trip['trip_id'],
onPressed: (pressed) => setState(()=> 'this is the place where it's not working'),
);
}),
);
},
)
onPressed
is typedef ValueChanged<in T> = void Function(T value)
. so I was trying to update list on button pressed.
this is the error message:
The instance member 'setState' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
2
Answers
It looks like you want to call setState inside the onPressed callback of a button in your ListView.builder widget that’s inside a FutureBuilder. The problem is that the setState method requires access to the State object of the widget, and you’re trying to call it from within the builder function. To achieve this, you need to move the FutureBuilder to a stateful widget and then use setState within that widget.
Here’s an example of how you can structure your Flutter code to achieve this
In this code:
MyWidget is a stateful widget that contains the FutureBuilder and the ListView.builder.
_fetchData is a method where you should fetch your data asynchronously. Replace the example code with your actual data fetching logic.
Inside the itemBuilder of the ListView.builder, you can call setState to update the widget’s state when the button is pressed. In this example, it removes the item from the list, but you can perform your specific update logic here.
Remember to replace the data fetching logic and other widget properties as per your application’s requirements.
From the error
The instance member 'setState' can't be accessed in an initializer.
seems like you need to pass your methods to theinitState
. You should init all your state properties ininitState
.if you are using FutureBuilder you can do something like this:
then call it in the
future: _future,
please refer to this answer