I want to add item in list when floatingAction
button is clicked.
class EditAgentVehiclesListScreen extends HookWidget {
final ValueNotifier<List<VehicleItems>> list;
const EditAgentVehiclesListScreen(this.list, {super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: AppTheme.light.colorScheme.primary,
onPressed: () {
Navigator.pushNamed(context, TenancyRoutes.createVehicleItemsScreen)
.then(((onValue) {
if (onValue is VehicleItems) {
debugPrint(onValue.toString());
list.value = [...list.value..add(onValue)]; // Corrected line
}
}));
},
child: const Icon(
Icons.add,
color: Colors.white,
)),
appBar: AppBar(
iconTheme: const IconThemeData(color: Colors.white),
backgroundColor: AppTheme.light.colorScheme.primary,
title: Text(
'vehicles'.tr(),
style: const TextStyle(color: Colors.white),
),
actions: const []),
body: _showBody(list),
);
}
Widget _showBody(ValueNotifier<List<VehicleItems>> list) {
return ListView.separated(
padding: EdgeInsets.zero,
shrinkWrap: true,
separatorBuilder: (context, index) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Container(
color: Colors.grey.shade200,
height: 1,
)),
itemCount: list.value.length,
itemBuilder: (context, index) {
final items = list.value[index];
return InkWell(
onTap: () {},
child: ListItemPadding(
child: VehicleItem(items),
// isDeleteVisible: false,
));
});
}
}
However, the list remain unchanged unless I hot reload it. How to fix?
2
Answers
You have to use a
StatefulWidget
and usesetState
every time that yourValueNotifier<List<VehicleItems>> list
updates, if you only use the list here though I would suggest putting that list inside of the state of theStatefulWidget
instead.If you still want to use the
ValueNotifier
then you have to add something like:You need to wrap your ListView to
ValueListenableBuilder
in order to listen to updates whenever it modifies thelist
(without using stateful widget)