PageView-在插入新项目时保留页面/更改索引

时间:2020-04-03 12:06:30

标签: flutter dart flutter-pageview

将新项目添加到列表时,PageView索引保持不变,但项目 随着索引的变化,我想避免这种行为。

要进一步指定,那些新项目会插入到列表的开头。

是否可以保存当前页面或将索引更改为正确的方法,以使页面保持不变?

下面的代码只是这个问题的简单实现。

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

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

class MyAppState extends State<MyApp> {
  List<String> pagesText = List.generate(10, (int index) => 'INDEX :: $index');

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.add),
              onPressed: () {
                setState(() {
                  pagesText.insert(0, 'INDEX :: ${pagesText.length + 1}');
                });
              },
            ),
          ],
        ),
        body: MyPageViewBuilder(pages: pagesText),
      ),
    );
  }
}

class MyPageViewBuilder extends StatelessWidget {
  final PageController pageController = PageController(keepPage: true);

  final List<String> pages;

  MyPageViewBuilder({this.pages});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: PageView.builder(
        controller: pageController,
        itemCount: pages.length,
        onPageChanged: (int index) {
          print('PageChanged $index');
        },
        itemBuilder: (BuildContext context, int index) {
          return Center(
            key: ValueKey(pages[index]),
            child: Text(pages[index]),
          );
        },
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

插入新项目后,您需要致电PageController.jumpToPage。但是,要执行此操作,您需要访问PageController中的MyAppState

首先,我向您的MyPageViewBuilder及其构造函数添加了一个新字段,并删除了旧的pageController字段:

// (...)
final PageController pageController;

MyPageViewBuilder({this.pages, this.pageController});
// (...)

然后,我将其添加到您的MyAppState

final pageController = PageController(keepPage: true);

onPressed中,我打电话给PageController.jumpToPage

setState(() {
  pagesText.insert(0, 'INDEX :: ${pagesText.length + 1}');
  pageController.jumpToPage(pageController.page.round() + 1);
});