首先,您需要创建一个FixedExtentScrollController,它允许您方便地使用项目索引,而不是使用标准ScrollController(来自Flutter doc)要求的原始像素滚动偏移量:
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() 将不起作用。
阅读this thread 了解更多关于如何在小部件构建完成时运行方法的信息