flutter - 让用户从 CupertinoPicker(onSelectedItemChanged) 中选择值,然后它应该发送调用到 API

标签 flutter flutter-cupertino

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

在文档中它被称为 CupertinoPicker > onSelectedItemChanged property

This can be called during scrolls and during ballistic flings. To get the value only when the scrolling settles, use a NotificationListener, listen for ScrollEndNotification and read its 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,
      ),
    );
  }

最佳答案

您可以检查 scrollNotificationmetrics 是否属于 FixedExtentMetrics 类型。此类型具有值 itemIndex,您可以使用它来确定当前选择的项目。

  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;
      }
    },

关于flutter - 让用户从 CupertinoPicker(onSelectedItemChanged) 中选择值,然后它应该发送调用到 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63915501/

相关文章:

flutter - 单击按钮后从方法中获取值后如何更改文本

flutter - 如何在 Flutter 中设置 CupertinoButton 的宽度?

flutter - 删除 flutter 警报对话框的灰色背景

flutter - 如何在 Flutter 中更改 CupertinoDatePicker 的字体大小?

flutter - CupertinoPicker textStyle flutter

dart - 在 CupertinoNavigationBar 中,我如何在前导中显示除后退按钮之外的按钮?

flutter - Sqflite或Shared Preference,它适合于在flutter中本地存储用户数据吗?

android - Flutter - 如何让 SnackBar 不向上插入 FloatingActionButton?

Flutter:如何避免 ListView 动态滚动(或改变其物理特性)

java - 如何在flutter中从RichText中检索文本值?