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