I'm new to flutter and trying to use two Stateful Widgets first one calling the second in build() method and I just want to update the child widget variable that is passed from parent in the constructor.
Here is the code I'm trying with.
Parent Widget
class Parent extends StatefulWidget {
Parent({Key? key}) : super(key: key);
@override
_ParentState createState() => _ParentState();
}
class _ParentState extends State<Parent> {
List appointments = [];
@override
void initState() {
super.initState();
fetchAppointments();
}
@override
Widget build(BuildContext context) {
return Builder(builder: (BuildContext context) {
return RefreshIndicator(
onRefresh: () async {
_pullRefresh();
},
child: ListView(
children: [
AppointmentsWidget(appointments: appointments) // <----- I passed the variable in constructor and this one is updating in setState and I want it to update in the child widget too
],
),
),
);
});
}
_pullRefresh() {
fetchAppointments();
}
fetchAppointments() {
setState(() {
// Stuff to do
appointments = ......
......
......
});
}
}
Child Widget
class AppointmentsWidget extends StatefulWidget {
var appointments;
AppointmentsWidget({this.appointments});
@override
_AppointmentsWidgetState createState() =>
_AppointmentsWidgetState(appointments: appointments); // <--- Constructor 1
}
class _AppointmentsWidgetState extends State<AppointmentsWidget> {
var appointments;
_AppointmentsWidgetState({this.appointments}); // <--- Constructor 2
@override
Widget build(BuildContext context) {
return ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: appointments.length,
itemBuilder: (BuildContext context, int index) {
return Text(appointments[index].toString()); // <--- This is where I use it
},
);
}
}
I know the constructor calls once but I couldn't find a way to either recall the constructor OR somehow pass the updated value to the constructor.
Your help is really appreciated.