0

将新项目添加到列表时,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]),
          );
        },
      ),
    );
  }
}
4

1 回答 1

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);
});
于 2020-04-03T12:26:13.380 回答