在 Flutter 的 ListView 中长按并滑动

Long key press and swipe in ListView in Flutter

我有一个正在创建 ListView 的屏幕。对于 Android 我想实现 "long key press"。 iOS 我想要 "swipe gesture"。

对于长按和滑动我必须显示 3 个选项:

Delete | Delete All | More...

怎么做。

将您的列表项 UI 包装在 Android 的 GetureDetector 中并使用 onLongTap 回调。对于 iOS,您可以将您的列表项 UI 包装在一个 Dissmissable 小部件中。一个简单的提取应该有助于解决这个问题。

将你的 UI 放在一个函数中,returns 只有你的 UI 用于该项目,然后根据平台用上面提到的外部包装它。

// import platform helpers
import 'package:flutter/foundation.dart' show defaultTargetPlatform;
import 'package:flutter/foundation.dart' show TargetPlatform;


// determine your platform
 final isIOS = defaultTargetPlatform == TargetPlatform.iOS;


// return your appropriate wrapper
isIOS 
? Dismissible(
  child: _getListItemUi(),
) 
: GestureDetector(
  onLongPress: () {
  },
  child: _getListItemUi()
);

Widget _getListItemUi() {
  return Container(child: Text('List Item UI'));
}

给你一个想法,你可以这样做。

@override
Widget build(BuildContext context) {
  bool isIos = Theme.of(context).platform == TargetPlatform.iOS;
  return ListView.builder(
    itemBuilder: (context, index) {
      if (isIos) {
        return Dismissible(
          key: Key("unique_key"),
          child: YourOwnWidget(),
          onDismissed: (direction) {
            // your item is swiped, perform operation here
          },
        );
      }
      return GestureDetector(
        onLongPress: () {
          // you can show an AlertDialog here with 3 options you need
        },
        child: YourOwnWidget(),
      );
    },
  );
}