François B.
François B.

Reputation: 31

Generate navigator buttons dynamically

I'm beginning with flutter and I'm trying to navigate to an other page with some buttons generated dynamically, but I need the buildcontext of my build everywhere... (Or maybe not, I'm not really sure to understand how to use it)

  class GamePage extends StatelessWidget {
        final Player p1;
        final Player p2;
        final List<Hexagon> arena;
    GamePage({this.p1, this.p2, this.arena});

    @override

    Widget getHexagon(Hexagon hcase) {
      Widget child;

    //if
    //else if

    //else =>
            child = RaisedButton(
            onPressed: nextTurn(),
            );

      Container container = new Container(
          child: child,
          );
      return container;
    }

    void nextTurn()
    {
      Navigator.push(/*here is the context needed*/, new MaterialPageRoute(
                      builder: (BuildContext context) =>
                         new GamePage(p1: p2, p2: p1, arena: arena,)));
    }

    List<Widget> getArena()
    {
      List<Widget> children = new List<Widget>();

        for (var hexagon in arena)
        {
          children.add(getHexagon(hexagon));
        }
      return children;
    }

    Widget build(BuildContext context) {

      return new Scaffold(
        body: 
        new Container(
            child: new GridView.count(
              children: getArena(),
            ),
          ),
      );
    }
}

Thanks in advance.

Upvotes: 0

Views: 56

Answers (1)

Tree
Tree

Reputation: 31371

You can enclose the function inside another one and once it is called, pass the context to _nextTurn

        child = RaisedButton(
          onPressed: (){
            _nextTurn(context)
          },
        );

Upvotes: 1

Related Questions