Флаттер: как перейти к последней странице, динамически создаваемой в PageView - PullRequest
0 голосов
/ 25 сентября 2018

У меня есть pageView, отображающий список страниц.

Приложение предоставляет кнопку + для добавления новой страницы в конце коллекции.

Мне нужно, чтобы pageView автоматически перешел кпоследняя страница после того, как эта новая страница была успешно создана.

Если я попытаюсь повторно отобразить представление, предоставляя провайдеру initialPosition, установленный на последний индекс pageView, он не будет работать

PageController(initialPage: 0, keepPage: false);

Любойидея реализации?

  • Использование слушателя (но какой слушатель?)

Полный код:

  @override
  Widget build(BuildContext context) {
    if (_userId == null) {
      return Scaffold(body: Center(child: Text("Loading experiences")));
    }
    print('Rebuilding entire view.');
    return Scaffold(
      appBar: new AppBar(
          title: StreamBuilder<ExperiencesInfo>(
              stream: _experiencesInfoStream,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  _selectedExperience = snapshot.data.currentExperience;
                  return Text(snapshot.data.currentExperience.name);
                } else {
                  return Center();
                }
              }),
          ),
      body: new Container(
        padding: new EdgeInsets.only(
          top: 16.0,
        ),
        decoration: new BoxDecoration(color: Colors.yellow),
        child: Column(
          children: <Widget>[
            Expanded(
                child:
                StreamBuilder<List<Experience>>(
                    stream: _userExperiencesStream,
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        return  _createExperiencesPagesWidget(snapshot.data);
                      } else {
                        return Center();
                      }
                    })
            ),
            _buildPageIndicator(),
            Padding(
              padding: EdgeInsets.only(bottom: 20.0),
            )
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
          child: new Icon(Icons.add),
          onPressed: () {
            _displayAddMenu();
          }),
    );
  }



_createExperiencesPagesWidget(List<Experience> experiences) {
    print('Creating ExperiencesPagesWidget ${experiences}');
    return PageView.builder(
      physics: new AlwaysScrollableScrollPhysics(),
      controller: _pageController,
      itemCount: experiences.length,
      itemBuilder: (BuildContext context, int index) {
        return ConstrainedBox(
            constraints: const BoxConstraints.expand(),
            child: Column(children: <Widget>[
              _buildMoodIndicator(experiences[index]),
              _buildMoodSelector(),
            ]));
      },
      onPageChanged: (index) {
        if (_actionType == ActionType.none) {
          print('page changed to index: ${index}, updating stream.');
          _experiencesViewModel.experienceIndexSink.add(index);
        } else {
          _actionType = ActionType.none;
        }

      },
    );

Контроллер страницы определен как свойство класса

PageController _pageController = PageController(initialPage: 0, keepPage: false);

1 Ответ

0 голосов
/ 25 сентября 2018

PageController содержит методы, которые вы можете использовать для динамического переключения между страницами.

// Create the page controller in your widget
PageController _controller = PageController(initialPage: 0, keepPage: false);


// Use it in your page view
@override
Widget build(BuildContext context) {
  ...
  PageView(controller: _controller, ...);
  ...
}


void onAddButtonTapped() {
  // add the new page
  ...

  // use this to animate to the page
  _pageController.animateToPage(lastIdx);

  // or this to jump to it without animating
  _pageController.jumpToPage(lastIdx);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...