Expanded(
flex: 10,
child: Container(
child: CupertinoPicker(
itemExtent: 50,
onSelectedItemChanged: (int i) {},
scrollController: FixedExtentScrollController(
initialItem: isIndex,
),
useMagnifier: true,
children: appwidget,
))),我有这个代码,孩子们是每一个改变列表的小部件。当我更改列表小部件的'appwidget‘时,我可以设置initialItem索引吗?
我不能给FixedExtentScrollController打电话。我没有头绪。
发布于 2021-08-11 11:39:44
首先,您需要创建一个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
https://stackoverflow.com/questions/65738898
复制相似问题