如何在Flutter中滚动或跳转到PageView.builder或PageController的位置?

slsn1g29  于 2023-01-27  发布在  Flutter
关注(0)|答案(4)|浏览(253)

问题:使用PageController加载页面视图后无法滚动到POSITION*

像ViewPager滚动到Android中的特定页面

Widget _buildCarousel(BuildContext context, int selectedIndex) {

    PageController controller = PageController(viewportFraction: 1, keepPage: true);
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        SizedBox(
          // you may want to use an aspect ratio here for tablet support
          height: 400.0,
          width: 240,
          child: PageView.builder(
            itemCount: assetImageList.length,
            controller: controller,
            itemBuilder: (BuildContext context, int itemIndex) {
              return _buildCarouselItem(context, selectedIndex, itemIndex);
            },
          ),
        )
      ],
    );
  }
pkbketx9

pkbketx91#

终于找到答案了。只需将***initialPage:**mSelectedPosition属性设置为:

child: PageView.builder(
        itemCount: mTemplateModelList.length,
        controller: PageController(initialPage: mSelectedPosition, keepPage: true, viewportFraction: 1),
        itemBuilder: (BuildContext context, int itemIndex) {
          return _buildCarouselItem(context, selectedIndex, itemIndex);
        },
      ),

或者,如果您想在单击按钮后滚动页面,则可以使用jumpTo()方法,该方法使用PageController,另一个用户在下面明确提到:@安卓。

3phpmpom

3phpmpom2#

目前有2个选项可处理您的请求:

PageView.builder(
  controller: _pageController,
  itemCount: _list.length,
  itemBuilder: (context, index) {
    return GestureDetector(
      onTap: () {
        _pageController.jumpToPage(index); // for regular jump
        _pageController.animateToPage(_position, curve: Curves.decelerate, duration: Duration(milliseconds: 300)); // for animated jump. Requires a curve and a duration
      },
      child: Container();
    );
  }
),
3qpi33ja

3qpi33ja3#

您可以使用jumpTo()方法滚动PageView的位置。我在下面的示例中创建了一个changePageViewPostion()方法:

import 'package:flutter/material.dart';

class MyPageView extends StatefulWidget {
  createState() {
    return StateKeeper();
  }
}

class StateKeeper extends State<MyPageView> {

  PageController controller = PageController(viewportFraction: 1, keepPage: true);
  var currentPageValue = 0.0;
  var mItemCount = 10;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller.addListener(() {
      setState(() {
        currentPageValue = controller.page;
      });
    });
  }

  void changePageViewPostion(int whichPage) {
    if(controller != null){
      whichPage = whichPage + 1; // because position will start from 0
      double jumpPosition = MediaQuery.of(context).size.width / 2;
      double orgPosition = MediaQuery.of(context).size.width / 2;
      for(int i=0; i<mItemCount; i++){
        controller.jumpTo(jumpPosition);
        if(i==whichPage){
          break;
        }
        jumpPosition = jumpPosition + orgPosition;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('PageView position change'),
      ),
      body: PageView.builder(
        controller: controller,
        itemBuilder: (context, position) {
          return Container(
            color: position % 2 == 0 ? Colors.blue : Colors.pink,
            child: Column(
              children: <Widget>[

                Center(
                  child: Text(
                    "Page " + (position + 1).toString(),
                    style: TextStyle(color: Colors.white, fontSize: 22.0),
                  ),
                ),

                Align(
                  alignment: FractionalOffset.bottomCenter,
                  child: Padding(padding: EdgeInsets.only(bottom: 20),
                    child: FloatingActionButton(
                        elevation: 0.0,
                        child: new Icon(Icons.check),
                        backgroundColor: new Color(0xFFE57373),
                        onPressed: (){
                          changePageViewPostion(5);
                        }
                    ),),
                ),

              ],
            ),
          );
        },
        itemCount: mItemCount,
      )
    );
  }

}

我们可以通过控制器获得当前位置,如下所示:

controller.addListener(() {
      setState(() {
        currentPageValue = controller.page.toInt();
        print((currentPageValue + 1).toString());
      });
    });

希望有帮助:)

ryevplcw

ryevplcw4#

如果您只想使用按钮滚动到下一页,您可以简单地使用以下方法。

//Create a PageController variable
  late PageController _pageController;
  
  //Initialize the variable in the init method.
  @override
  void initState() {
    _pageController = PageController(
        initialPage: _activePage, keepPage: true, viewportFraction: 1);
    super.initState();
  }

  //Use this nextPage() method in the onPressed() method.
  onPressed: () {
    setState(() {
      _activePage < 2
         ? _activePage++
         : Navigator.pushReplacementNamed(
             context, LoginScreen.id);
    });

    _pageController.nextPage(
      duration: const Duration(milliseconds: 300),
      curve: Curves.decelerate,
    );
  }

相关问题