acincognito
acincognito

Reputation: 1743

setState doens't cause re-render of new screen in flutter

I got a List, called savedListsList, that contains a list of Objects. When the app starts this list is empty. When the users clicks on a PopupMenuItem (depicted in the case 0: case), data is loaded from an internal database and after that, a new screen shows up where the data is shown (basically a StatelessWidget that contains a ListView.builder with a certain amount of rows).

Every row consists of a GestureDetector that listens for left and right swipes. On every of these swipes updateSaveListItem is called. According to the beingEdited attribute the appearance of the row inside the before mentioned ListView.builder is changed.

I know that the swipes trigger the attribute to change accordingly, since I printed that out.

Unfortunately the change in updateSavedListItem doesn't cause a re-render of the current screen. When I hot-reload the app the change of beingEdited is reflected.

I'm pretty sure that I can get this to work, when I turn the widget that surrounds the ListView.builder into a StatefulWidget. But my question is: can I trigger a re-render of the current page with the architecture I described? Since I want to keep as much of my state management as I can inside my _MainPage class.

class _MainPage extends State<MainPage> {
List<SavedListObj> savedListsList = List();

  @override
  void initState() {
   savedListsList = List();
  }

  void updateSavedListItem(int id, String action, String newName) {
   setState(() {
    switch (action) {
     case 'beingEditedStart':
       savedListsList[id].beingEdited = true;
      break;
     case 'beingEditedEnd':
       savedListsList[id].beingEdited = false;
      break;
     case 'delete':
      break;
     case 'edit':
      break;
    }
   });
  }

  @override
  Widget build(BuildContext context) {

   return Scaffold(
    appBar: AppBar(
    actions: <Widget>[
      PopupMenuButton(
        onSelected: (value) {
          switch (value) {
            case 0:
             DB db = DB();
              db.getListNames().then((queryResult) {
                savedListsList.clear();
                setState(() {
                  savedListsList.addAll(queryResult);
                });

                Navigator.push(
                 context,
                 MaterialPageRoute(
                  builder: (context) => SavedListsPage(
                            savedListsList,
                            updateSavedListItem,
                           ),
                       ),
                  );
             break;
          }
        },
       ),
      ],
     ),
    );
   }
}

Upvotes: 0

Views: 2895

Answers (1)

Yash
Yash

Reputation: 5978

No you cannot do that! you have to use Stateful widget when you have to update the state of your app. For futher reference you can refer this link.

Upvotes: 1

Related Questions