flutterwidgetstackrebuild

Flutter Rebuild Widget via Stack List


It is more a beginners question about updating the properties of a widget. But I have a hard time finding an answer in the forum about the following: In an external class (b1) I am storing the properties of my widgets in a list (tileListe). The build method looks as follows:

 @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Stack(
        children: b1.tileList,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            b1.tileList[12].text= 'abc';   // Does not update 
            b1.tileList[12].pos.y = 10.0;  // Does not update 
            b1.tileList.removeAt(0);       // Updates when Button is pushed
          });
        },
        child: const Icon(Icons.remove),
      ),
    );
   }

The widgets in tileList are equipped with a ValueKey(<>), where the counting starts from 1. It is taken care that the keys and index of the list do not interfere each other.

I want to update the first (set text to abc) and second (set y-Position to 10 for my widget with index 12) property and see the change immediately. But this happens only after a "Hot Restart" from Andriod Studio.

In contrast the third command (remove the widget with index 0) is updated immediately. What is different from the first and second command to the third in regard to their visible update behavior? How can I get all three changes made visible directly?


Solution

  • Assuming the tileList contains Widgets, by calling setState() in the build() you won't rebuild these widgets from b1.titleList. My solution is to write somethig like this:

    Function?() _setStateTemp;
    
    void refresh() {
        _setStateTemp?();
    }
    
    @override
    Widget build(BuildContext context) {
        _setStateTemp = setState((){}); //add this line
        [the rest of your code...]
    }
    
    void refreshList() {
        for (<your-type-of-titleList> tl in titleList) {
            tl.refresh();
        }
    }
    
    @override
    Widget build(BuildContext context) {
     return Scaffold(
       body: Stack(
         children: b1.tileList,
       ),
       floatingActionButton: FloatingActionButton(
         onPressed: () {
           setState(() {
             b1.tileList[12].text= 'abc';   
             b1.tileList[12].pos.y = 10.0;  
             b1.tileList.removeAt(0);     
             b1.refreshList(); //add this line
           });
         },
         child: const Icon(Icons.remove),
       ),
     );
    }
    

    Hope it will help. I wrote this without IDE so I could make some mistakes. Ask is anything is not clear. Cheers!