0

When adding new items to list, PageView index stays the same, but item with that index changes and I would like to avoid that behavior.

To be more specified those new items are inserted to the begging of the list.

Is there a way to preserve current page or method to change index to the right one so the page will stay the same?

Code below is just a simple implementation of this problem.

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]),
          );
        },
      ),
    );
  }
}
hydeparkk
  • 62
  • 1
  • 7

1 Answers1

0

You need to call PageController.jumpToPage after inserting new item. To do this though, you need to have access to PageController in your MyAppState.

Firstly, I added a new field to your MyPageViewBuilder and its constructor and removed the old pageController field:

// (...)
final PageController pageController;

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

Then, I added it to your MyAppState:

final pageController = PageController(keepPage: true);

and in onPressed I'm calling PageController.jumpToPage:

setState(() {
  pagesText.insert(0, 'INDEX :: ${pagesText.length + 1}');
  pageController.jumpToPage(pageController.page.round() + 1);
});
Albert221
  • 5,223
  • 5
  • 25
  • 41
  • I've update the question, those new elements are inserted to the beginning of the list and that the case. – hydeparkk Apr 03 '20 at 13:05