简体   繁体   English

从小部件外部访问 State 变量

[英]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因此,我制作了PageViewer ,但无法在其中使用Navigator ,而我想做的是使用返回函数的StatefulWidget在内部传递不同的小部件,我想访问所述StatefulWidget并更改其中的变量它,找不到办法做到这一点

This is the PageView :这是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:这是我用来在页面中传递的StatefulWidget

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).您不需要StatefulWidget只是为了包含另一个Widget (在本例中为ChooseAccount )。 If I understand your question correctly, you want to change the PageView dynamically right?如果我正确理解您的问题,您想动态更改PageView吗? 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:然后,您可以简单地使用PageView中的此页面列表与PageController结合在页面之间导航:

  // 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,
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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