Как прокрутить или перейти в положение PageView.builder или PageController во Flutter? - PullRequest
1 голос
/ 09 мая 2019

Проблема: невозможно перейти к ПОЛОЖЕНИЮ после загрузки просмотров страниц с помощью PageController *

, как 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);
            },
          ),
        )
      ],
    );
  }

Ответы [ 3 ]

1 голос
/ 09 мая 2019

Наконец-то нашел ответ.Просто установите атрибут 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 , который явно указан ниже другим пользователем: @ android.

1 голос
/ 09 мая 2019

Вы можете использовать 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());
      });
    });

Надеюсь, это поможет:)

0 голосов
/ 06 июля 2019

В настоящее время есть 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();
    );
  }
),
...