Home > Software engineering >  Flutter update refresh previous page when page has been pushed via a stateless widget
Flutter update refresh previous page when page has been pushed via a stateless widget

Time:10-10

So here is the problem. TabScreen() with 3 pages and one fabcontainer button (Stateless widget). When pressed the fabcontainer will give you the chances of make one upload, after the upload i would like to refresh one of the page of the tabscreen.

    return Container(
      height: 45.0,
      width: 45.0,
      // ignore: missing_required_param
      child: FabContainer(
        icon: Ionicons.add_outline,
        mini: true,
      ),
    );
  }

OnTap of the fabcontainer:

                  Navigator.pop(context);
                  Navigator.of(context).push(
                    CupertinoPageRoute(
                      builder: (_) => CreatePost(),
                    ),
                  );
                },

Cannot add a .then(){setState... } because it is a stateless widget and i need to set the state of a precise page, not of the fabcontainer.

Any idea?

Thanks!

CodePudding user response:

Define a updateUi method inside your TabScreen (which defines the pages)

TabScreen:

void updateUi(){
 // here your logic to change the ui
 // call setState after you made your changes
 setState(() => {});
}

Pass this function as a constructor param to your FabContainer button

FabContainer(
        icon: Ionicons.add_outline,
        mini: true,
        callback: updateUi,

      ),

Define it in your FabContainer class

final Function() callback;

Call it to update the ui

callback.call();

CodePudding user response:

So what Ozan suggested was a very good beginning but i could not access the stateful widget in order to set the state.

What i did on top of Ozan's suggestion was giving the state a globalkey:

final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

Assigning it to the scaffold:

return Scaffold(
      key: scaffoldKey,

Making the state public removing the _MyPizzasState -> MyPizzasState

Creating a method to refresh the data:

  refreshData() {
    pizzas = postService.getMyPizzas();
    setState(() {

    });
  }

Assigning a key during the creation of the MyPizzaPage:

final myPizzasKey = GlobalKey<MyPizzasState>();
{
      'title': 'My Pizza',
      'icon': Ionicons.pizza_sharp,
      'page': MyPizzas(key: myPizzasKey),
      'index': 0,
    },

And, how Ozan said once i received the callback :

 buildFab() {
    return Container(
      height: 45.0,
      width: 45.0,
      // ignore: missing_required_param
      child: FabContainer(
        icon: Ionicons.add_outline,
        mini: true,
        callback: refreshMyPizzas,
      ),
    );
  }

  void refreshMyPizzas() {
    print("Refreshing");
    myPizzasKey.currentState?.refreshData();
  }
  • Related