从小部件外部访问状态变量

时间:2021-03-12 01:43:42

标签: android flutter dart flutter-navigation statefulwidget

所以我制作了 PageViewer 并且我无法在其中使用 Navigator,而是我想要做的是使用 StatefulWidget 在内部传递不同的小部件返回函数, 我想访问上述 StatefulWidget 并更改其中的变量,但找不到方法

这是PageView

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

这是我用来在页面中传递的 StatefulWidget

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

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

var _page = ChooseAccount();

return _page;
  }
}

1 个答案:

答案 0 :(得分:0)

您不需要一个 StatefulWidget 来包含另一个 Widget(在本例中为 ChooseAccount)。如果我正确理解您的问题,您想动态更改 PageView 对吗?在这种情况下,您可以执行以下操作:

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

然后您可以简单地使用 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,
)