2

我正在为 iOS 用户使用 CupertinoWidget 来滚动列表并检查货币的价格。但是当滚动发生时,onSelectedItemChanged会针对列表中的每个值向 API 发送回调。我阅读了文档,但无法理解该怎么做。如果有例子就很高兴。

在文档中它被称为CupertinoPicker > onSelectedItemChanged 属性

这可以在卷轴和弹道投掷期间调用。要仅在滚动稳定时获取值,请使用 NotificationListener,侦听 ScrollEndNotification 并读取其 FixedExtentMetrics。

 NotificationListener cupertinoPickerList() {
    List<Text> textWidgetList = [];
    for (String curreny in currenciesList) {
      textWidgetList.add(
        Text(
          curreny,
          style: TextStyle(
            color: Colors.white,
          ),
        ),
      );
    }
    return NotificationListener<ScrollNotification>(
      onNotification: (scrollNotification) {
        if (scrollNotification is ScrollEndNotification) {
          return true;
        } else {
          return false;
        }
      },
      child: CupertinoPicker(
        itemExtent: 30,
        scrollController: FixedExtentScrollController(initialItem: 19),
        onSelectedItemChanged: (selectedIndex) {
          selectedCurreny = currenciesList[selectedIndex];
          updateUI(selectedCurreny);
          print(selectedCurreny);
        },
        children: textWidgetList,
      ),
    );
  }
4

2 回答 2

2

您可以检查are 的类型是否metrics为。此类型具有值 itemIndex,您可以使用它来确定当前选择了哪个项目。scrollNotificationFixedExtentMetrics

  return NotificationListener<ScrollNotification>(
    onNotification: (scrollNotification) {
      if (scrollNotification is ScrollEndNotification &&
      scrollNotification.metrics is FixedExtentMetrics) {
        (scrollNotification.metrics as FixedExtentMetrics).itemIndex; // Index of the list
        return true;
      } else {
        return false;
      }
    },
于 2021-05-21T08:00:02.487 回答
0

借助Julantje15的代码,这里有一个完整的解决方案:

final widget = NotificationListener<ScrollEndNotification>(
  onNotification: (notification) {
    if (notification.metrics is! FixedExtentMetrics) {
      return false;
    }

    final index = (notification.metrics as FixedExtentMetrics).itemIndex;

    // This would be your callback function. Could use items[index]
    // or something if that's more appropriate of course.
    onItemChanged(index);

    // False allows the event to bubble up further
    return false;
  },
  child: CupertinoPicker(
    itemExtent: 32,
    onSelectedItemChanged: null, // Attribute is marked required
    children: [Text('item1'), Text('item2'), Text('etc')], 
  ),
);

想要这个似乎很明智,所以我想这不作为(可选)默认行为包括在内有点奇怪。我想如果更频繁地需要它,你可以将包装器变成一个自定义小部件。

于 2021-11-18T17:27:27.140 回答