Home > front end >  Flutter: Is there a way to change the contents of a card from another button?
Flutter: Is there a way to change the contents of a card from another button?

Time:04-04

I am currently developing a manpower app which displays a few groups of people and their details. I have a row of buttons at the top of the card which display the groups of people available. Below the row of buttons is a card which displays the details of each individual in rows.

However, I am unable to change the bottom card even when pressing the top button corresponding to the card. I have tried using setState(), and even navigating out and back into the page (to refresh the build). However, the bottom card remains the same, and always displays section 1, which is the initial value given to the card. How am I able to change the bottom card, after pressing the top row button corresponding to the card?

The code is below-

int section = 4;
int currentSectionSelected = 1;

@override
void initState() {
  loadSectionDetails();
  super.initState();
}

void loadSectionDetails() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  setState(() {
    section = (prefs.getInt('sectionCounter') ?? 4);
    currentSectionSelected = (prefs.getInt('currentSectionSelected') ?? 1);
  });
}

void currentSectionSelection(int sectionSelected) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt('currentSectionSelected', sectionSelected);
    setState(() {
      currentSectionSelected = sectionSelected;
    });
 }

@override
Widget build(BuildContext context) {

  List<Widget> sectionList = List.generate(section, (int i) =>
      TextButton(
        child: Text("Section " (i 1).toString()),
        onPressed: () {
            currentSectionSelection(i 1);
        },
      )
  );

return Card (
  child: Column(
    children: <Widget>[
      Row(
         children: sectionList
      ),
      Card(
         child: PersonnelSection(sectionNumber: currentSectionSelected)
      )
    ]
  )
);

PersonnelSection() is the name of another widget.

The image is here

Thanks all!

CodePudding user response:

If PersonnelSection is a StatefulWidget, pass the key to it like this

Card(
      child: PersonnelSection(
        sectionNumber: currentSectionSelected,
        key: ValueKey(currentSectionSelected),
      ),
    );
  • Related