Flutter中如何设置PageView的初始页面? [英] How do I set the initial page of PageView in Flutter?

查看:18
本文介绍了Flutter中如何设置PageView的初始页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have a PageView with four pages in it. I want to start on the third page. That means there are two pages available when the user scrolls up and one page when the user scrolls down.

I tried:

home: PageView(
   controller: MyPageController(),
   children: [Page1(), Page2(), Page3(), Page4()],
   scrollDirection: Axis.vertical,
),

With:

class MyPageController extends PageController {
   @override
   int get initialPage => 3;
}

Unfortunately, that doesn't help me.

解决方案

PageController constructor has named parameter initialPage. You can use it, just create the controller somewhere outside of build function:

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  PageController controller;

  @override
  void initState() {
    super.initState();
    controller = PageController(initialPage: 3);
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: PageView(
            controller: controller,
            children: [
              for (var i = 0; i < 4; i++)
                Text('test $i')
            ],
            scrollDirection: Axis.vertical,
          )
        )
      ),
    );
  }
}

这篇关于Flutter中如何设置PageView的初始页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆