简体   繁体   中英

Access State variable from outside the widget

So I've made PageViewer and I wasn't able to use Navigator inside of it, instead what I'm trying to do is to pass diferrent widget inside using StatefulWidget that return functions, I want to access said StatefulWidget and change variable inside of it, couldn't find a way to do it

This is the PageView :

Expanded(
            child: PageView(
              children: [
                SetPage(), // Look at the bottom need to be changeable
                ],
            ),
          ),

and this is the StatefulWidget I use to pass in the page:

class SetPage extends StatefulWidget {
  @override
_SetPageState createState() => _SetPageState();
}

class _SetPageState extends State<SetPage> {
  @override
  Widget build(BuildContext context) {

var _page = ChooseAccount();

return _page;
  }
}

You don't need a StatefulWidget just to contain another Widget ( ChooseAccount in this case). If I understand your question correctly, you want to change the PageView dynamically right? In that case you can do something like this:

  // List of pages in your app
  List<Widget> pages = [
    ChooseAccount(), // The choose account page
    Container(
      color: Colors.blue,
    ), // Some other pages
    Container(
      color: Colors.green,
    ),
  ];

You can then simply use this list of pages in the PageView combined with PageController to navigate between pages:

  // Define the controller here
  PageController _controller = PageController(initialPage: 0);

  // Use this method to navigate between pages (for example when changing tabs in the TabBar`
  navigateToPage(int index) {
    _controller.jumpToPage(index);
  }

// Use the controller and the pages with the PageView
PageView(
    controller: _controller,
    physics: NeverScrollableScrollPhysics(),
    children: pages,
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM