如何更改页面浏览量页面的显示顺序- Flutter

0vvn1miw  于 2023-04-07  发布在  Flutter
关注(0)|答案(2)|浏览(159)

我想根据用户的操作改变页面的显示顺序,如果他点击按钮1,红色页面首先显示,如果他点击按钮2,黄色页面首先显示。
如何更改页面的顺序?
我使用pageview.builder是正确的吗?

class PageViewTest extends StatefulWidget {
  const PageViewTest({super.key});

  @override
  State<PageViewTest> createState() => _PageViewTestState();
}

class _PageViewTestState extends State<PageViewTest> {
  final _pageController = PageController();
  @override
  Widget build(BuildContext context) {
    return PageView(
      controller: _pageController,
      children: [
        Column(
          children: [
            TextButton(
                onPressed: () {
                  //show container red with next page
                },
                child: const Text("Button 1")),
            TextButton(
                onPressed: () {
                  //show container yellow next page
                },
                child: const Text("Button 2")),
          ],
        ),
        Container(
          color: Colors.red,
        ),
        Container(
          color: Colors.yellow,
        ),
      ],
    );
  }
}
bnl4lu3b

bnl4lu3b1#

试试这样

class PageViewTest extends StatefulWidget {
  const PageViewTest({Key? key}) : super(key: key);

  @override
  _PageViewTestState createState() => _PageViewTestState();
}

class _PageViewTestState extends State<PageViewTest> {
  final _pageController = PageController();
  int _currentPageIndex = 0;

  @override
  Widget build(BuildContext context) {
    return PageView.builder(
      controller: _pageController,
      itemCount: 2,
      itemBuilder: (BuildContext context, int index) {
        switch (index) {
          case 0:
            return Column(
              children: [
                TextButton(
                  onPressed: () {
                    setState(() {
                      _currentPageIndex = 1;
                    });
                  },
                  child: const Text("Button 1"),
                ),
                TextButton(
                  onPressed: () {
                    setState(() {
                      _currentPageIndex = 2;
                    });
                  },
                  child: const Text("Button 2"),
                ),
              ],
            );
          case 1:
            return Container(
              color: Colors.red,
            );
          case 2:
            return Container(
              color: Colors.yellow,
            );
          default:
            return Container();
        }
      },
    );
  }
}
az31mfrm

az31mfrm2#

您可以使用PageView.builder或普通PageView,两者都可以工作。
至于页面的改变,你应该使用传入PageViewPageController,如果你不想要动画,在你的按钮中调用_pageController.animateToPage(pageNumber)_pageController.jumpToPage(pageNumber)

相关问题