flutter - 如何将列表视图滚动到索引?
问题描述
我有一个字符串列表,这些字符串构成了水平创建的项目菜单:
List categories = ['Interest', 'Preferences', 'Personal Information', 'Hobbies',];
当用户选择其中一项时,特定信息会呈现到屏幕上。
我的问题是,例如,如何水平滚动此菜单;有 5 个选项,用户只能看到屏幕中的 3 个项目,如果他/她选择第二个项目,则该项目向左移动,隐藏第一个并显示第 4 个。
我想过ScrollablePositionedList()
但不知道如何使用它。
class CategoryListState extends State<CategoryList> {
static const colorBlau = Color(0xFF88B4E0);
int selectedIndex = 0;
List categories = ['Interest', 'Preferences', 'Personal Information', 'Hobbies',];
//Your list of widgets that you import, note: keep the order same as categories
List<Widget> category_widgets = [CheckBoxes(), DropDownWidget(), TextFields(), SwipeCards(),];
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
margin: EdgeInsets.symmetric(vertical: 20.0/2),
height: 30.0,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: categories.length,
itemBuilder: (context, index) => GestureDetector(
onTap: () {
setState(() {
selectedIndex = index;
//categories[index].isSelected = true;
});
},
child: Container (
alignment: Alignment.center,
margin: EdgeInsets.only(
left: 20.0,
right: index == categories.length -1 ? 20.0 : 0,
),
padding: EdgeInsets.symmetric(horizontal: 20.0),
decoration: BoxDecoration(
color: index == selectedIndex
? Colors.white.withOpacity(0.4)
: Colors.transparent,
borderRadius: BorderRadius.circular(6),
),
child: Text(
categories[index].toString(),
style: TextStyle(color: Colors.white),
),
),
),
),
),
category_widgets[selectedIndex],
],
);
}
}
解决方案
您可以通过这种方式使用 ScrollablePositionedList
final ItemScrollController itemScrollController = ItemScrollController();
final ItemPositionsListener itemPositionsListener = ItemPositionsListener.create();
ScrollablePositionedList.builder(
itemCount: 500,
itemBuilder: (context, index) => Text('Item $index'),
itemScrollController: itemScrollController,
itemPositionsListener: itemPositionsListener,
);
然后可以滚动到特定项目:
itemScrollController.scrollTo(
index: 150,
duration: Duration(seconds: 2),
curve: Curves.easeInOutCubic);
或跳转到特定项目:
itemScrollController.jumpTo(index: 150);
推荐阅读
- machine-learning - 如何预测对象的状态
- angular - Angular Service 未命中,功能未定义 TypeScript
- azure - 部署 Azure 虚拟机规模集并使用来自 VSTS 的多个网站安装 IIS
- javascript - 如何通过点击获取该用户的数据?
- css - 使用 RazorEngine 在 `cshtml` 中使用外部 CSS
- svg - 是否使用
包括重用多个 SVG 时减少页面重量? - xml - Powerbuilder - XML - 基本身份验证
- xcode-ui-testing - XCUIElement 唯一标识符
- angular - 用于将当前日期与选定日期进行比较的 Angular 6 自定义验证器未正确验证并允许添加任何值
- python - py.test 未正确从 conftest 导入模块 - 因 ConftestImportFailure: ModuleNotFound 而失败