首先,您需要创建一个FixedExtentScrollController
,它允许您方便地使用项目索引,而不是使用标准要求的原始像素滚动偏移量ScrollController
(来源来自Flutter 文档):
FixedExtentScrollController? _scrollWheelController;
final String? value;
final String values = ['male','female','other'];
@override
void initState() {
super.initState();
_scrollWheelController = FixedExtentScrollController(
/// Jump to the item index of the selected value in CupertinoPicker
initialItem: value == null ? 0 : values.indexOf(value!),
);
}
然后将其连接到,CupertinoPicker
以便您可以通过编程方式控制滚动视图:
CupertinoPicker.builder(scrollController: _scrollWheelController);
ModalBottomSheet
如果您想在弹出时立即跳转到所选值的项目索引,以下代码将帮助您实现此目的:
showModalBottomSheet<String>(
context: context,
builder: (_) {
/// If the build() method to render the
/// [ListWheelScrollView] is complete, jump to the
/// item index of the selected value in the controlled
/// scroll view
WidgetsBinding.instance!.addPostFrameCallback(
/// [ScrollController] now refers to a
/// [ListWheelScrollView] that is already mounted on the screen
(_) => _scrollWheelController?.jumpToItem(
value == null ? 0 : values.indexOf(value!),
),
);
return SizedBox(
height: 200,
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: TextButton(
onPressed: () => Navigator.pop(context),
child: Text('Done'),
),
),
const Divider(thickness: 1),
Expanded(
child: CupertinoPicker.builder(
/// if [itemExtent] is too low, the content for each
/// item will be squished together
itemExtent: 32,
scrollController: _scrollWheelController,
onSelectedItemChanged: (index) => setState(() => values[index]),
childCount: values.length,
itemBuilder: (_, index) => Center(
child: Text(
valueAsString(values[index]),
style: TextStyle(
color: Theme.of(context).accentColor,
),
),
),
),
),
],
),
);
},
);
WidgetsBinding.instance!.addPostFrameCallback()
将确保build()
当前帧中要渲染的所有小部件的所有方法都是完整的。如果_scrollWheelController
指的ListWheelScrollView
是尚未完全构建的,jumpToItem()
则将不起作用。
阅读此线程以获取有关如何在 Widget build complete 上运行方法的更多信息