Narendar Singh Saini
Narendar Singh Saini

Reputation: 3394

Long key press and swipe in ListView in Flutter

I have a screen where I am creating a ListView. For Android I want to implement "long key press". For iOS I want "swipe gesture".

For long key press and swipe I have to show 3 options:

Delete | Delete All | More...

How to do that.

Upvotes: 0

Views: 2707

Answers (2)

CopsOnRoad
CopsOnRoad

Reputation: 268464

To give you an idea you can do this.

@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(),
      );
    },
  );
}

Upvotes: 2

Filled Stacks
Filled Stacks

Reputation: 4356

Wrap your listitem UI in a GetureDetector for Android and use the onLongTap callback. For iOS you can wrap your listitem UI in a Dissmissable widget. A simple extraction should help with that.

Have your UI in a function that returns only your UI for the item, then outside wrap it with the above mentioned based on the platform.

// 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'));
}

Upvotes: 1

Related Questions