funnybunny
funnybunny

Reputation: 117

Child widget not updating parent widget when child parameter changes

I have a child stateful widget that isn't updating the parent widget when an update to one of the parameters occurs. The parent widget (OtherListVIew) is used to display a list of items on a PaginatedGrid with each item having a checkbox. The problem is that when a user views the page and there are selected items that are retrieved by the _retrieveItems() the changes do not reflect since at this point the ui is already rendered on the screen with the original empty list. These retrieved values do not reflect on OtherListView (_selectedItems is then used to display the checked items).

In this child widget I have the code

List<String> _selectedItems= [];

@override
void didChangeDependencies() {
 super.didChangeDependencies();
 WidgetsBinding.instance.addPostFrameCallback((_) {
  _retrieveItems(); // this function retrieves items and reinitializes _selectedItems
 });
}

@override
Widget build(BuildContext context) {
 return SomeListView(
   key: _listViewKey,
   selectedItems: _selectedItems,
 );
}

SomeListView looks as below

class SomeListView extends OtherListView {

const SomeListView ({super.key, super.selectedItems});

@override
State<SomeListView > createState() => SomeListViewState();
}

class SomeListViewState extends OtherListViewState<SomeListViewState> {
 // override some method here from OtherListView for customization purposes

 @override
 Widget build(BuildContext context) {
   return super.build(context);
 }
}

OtherListView is the parent class that contains the PaginatedGrid that renders the passed _selectedItems to the UI. Why is it that after the _selectedItems have been refetched they are not reflecting on OtherListView? Is this an issue with my state management?

I have attempted using didUpdateWidget under OtherListView and indeed I can see the new values under the newWidget but they are not rendered on the UI. What I'm I missing?

@override
void didUpdateWidget(covariant T oldWidget) {
  super.didUpdateWidget(oldWidget);
  if (widget.selectedItems != oldWidget.selectedItems) {
    log.info('OtherListView selected items have been updated.');
  }
}


OtherListView extends StatefulWidget {
  final List<String>? selectedItems;

  const OtherListView({Key? key,this.selectedItems})
     : super(key: key);
  
  // ...
}

Upvotes: 0

Views: 420

Answers (1)

CCP
CCP

Reputation: 1236

honestly i don't understand your code but the problem you are facing the parameter is not updating because with setState it will only rebuild the parameter/state/variables that are in the same screen/class widget where the setState is called so you have to raise your parameter to the parent screen then pass it to the child with constructor and create a constructor in your child for function onTap for example then in the parent screen you use that onTap and called setState inside

Upvotes: 1

Related Questions