我有一个PageView可以处理三个不同长度的数据列表。清单1有一项,清单2有2项,清单3有3项。这是正在发生的事情。
我尝试在build方法中使用WidgetsBinding.instance.addPostFrameCallback(...)构建PageView之后调用jumpToPage(2),以为PageController正在某个地方读取旧的itemCount = 2值。那没用。
如何基于新的PageView itemCount = 3使jumpToPage(2)工作?
这是我的代码。我试图使它尽可能简单。
import 'package:flutter/material.dart';
class HomePage2 extends StatefulWidget {
@override
_HomePage2State createState() => _HomePage2State();
}
class _HomePage2State extends State<HomePage2> {
List<Map<String, dynamic>> following = [
{'title': 'Page 1 of 1 following', 'color': Colors.purple.value},
];
List<Map<String, dynamic>> suggested = [
{'title': 'Page 1 of 2 suggested', 'color': Colors.purple.value},
{'title': 'Page 2 of 2 suggested', 'color': Colors.red.value},
];
List<Map<String, dynamic>> trending = [
{'title': 'Page 1 of 3 trending', 'color': Colors.purple.value},
{'title': 'Page 2 of 3 trending', 'color': Colors.red.value},
{'title': 'Page 3 of 3 trending', 'color': Colors.orange.value},
];
String currentFeed = 'suggested';
int followingCurrentPosition = 0;
int suggestedCurrentPosition = 0;
int trendingCurrentPosition = 0;
PageController _pageController;
@override
void initState() {
super.initState();
_pageController = PageController();
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
print('build');
WidgetsBinding.instance.addPostFrameCallback(
(_) => _pageController.jumpToPage(getCurrentFeedPosition()));
return Scaffold(
body: PageView.builder(
itemCount: getCurrentFeed().length,
scrollDirection: Axis.vertical,
controller: _pageController = PageController(viewportFraction: 1),
itemBuilder: (context, index) {
print('PageView itemBuilder');
return Container(
color: Color(getCurrentFeed()[index]['color']),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Text(getCurrentFeed()[index]['title']),
),
Center(
child: RaisedButton(
onPressed: () => changeCurrentFeed(),
child: Text('Change Feed'),
),
),
],
),
);
},
),
);
}
void changeCurrentFeed() {
setState(
() {
if (currentFeed == 'following') {
followingCurrentPosition = _pageController.page.floor();
currentFeed = 'suggested';
} else if (currentFeed == 'suggested') {
suggestedCurrentPosition = _pageController.page.floor();
currentFeed = 'trending';
} else {
trendingCurrentPosition = _pageController.page.floor();
currentFeed = 'following';
}
},
);
}
List<Map<String, dynamic>> getCurrentFeed() {
if (currentFeed == 'following') {
return following;
} else if (currentFeed == 'suggested') {
return suggested;
} else {
return trending;
}
}
int getCurrentFeedPosition() {
if (currentFeed == 'following') {
return followingCurrentPosition;
} else if (currentFeed == 'suggested') {
return suggestedCurrentPosition;
} else {
return trendingCurrentPosition;
}
}
}
答案 0 :(得分:0)
此行为似乎是由于PageView itemBuilder在每次构建中均被多次调用引起的。其他人有这个问题,但是我找不到解决方案。我最终为每个列表使用了单独的PageView,而不是尝试将一个PageView与多个列表一起使用。这为我解决了。