mydomain
No ADS
No ADS

FlutterArtist Manual Sorting ReorderableListView

  1. Structure of the example
  2. Currency49aShelf
  3. Currency49aReorderableListItemsView
In programming, "Manual sorting" refers to the process of organizing data elements in a specific order defined by the user, rather than relying on built-in sorting functions or automated algorithms. Instead, the application allows users to rearrange elements directly through Drag & Drop interactions.
Demo49a
Trong bài viết này, chúng ta sẽ khám phá cách sử dụng ReorderableListView, một widget tiêu chuẩn của Flutter, kết hợp với hệ sinh thái FlutterArtist để hiện thực hóa tính năng này.
  • Download FlutterArtist Demo
See also similar examples, manual sorting with SortableGridView:

1. Structure of the example

2. Currency49aShelf

In FlutterArtist, to enable manual reordering of ITEM(s) on the client-side, the prerequisite is setting the sorting strategy in BlockConfig to SortStrategy.manual.
No ADS
currency49a_shelf.dart
class Currency49aShelf extends Shelf {
  @override
  ShelfStructure defineShelfStructure() {
    return ShelfStructure(
      filterModels: {},
      blocks: [
        Currency49aBlock(
          name: Currency49aBlock.blkName,
          description: null,
          config: BlockConfig(clientSideSortStrategy: SortStrategy.manual),
          filterModelName: null,
          formModel: null,
          childBlocks: [],
        ),
      ],
    );
  }

  Currency49aBlock findCurrency49aBlock() {
    return findBlock(Currency49aBlock.blkName) as Currency49aBlock;
  }
}
See more automatic sorting examples based on SortModel:

3. Currency49aReorderableListItemsView

We use the .builder() constructor of ReorderableListView to optimize performance for long lists.
Currency49aReorderableListItemsView (**)
Widget buildContent(BuildContext context) {
  List<CurrencyInfo> currencyInfos = block.items;
  //
  return ReorderableListView.builder(
    padding: EdgeInsets.all(5.0),
    itemCount: currencyInfos.length,
    onReorder: _onReorder,
    itemBuilder: (context, index) {
      CurrencyInfo currencyInfo = currencyInfos[index];
      return Currency49aListItem(
        key: Key("Currency-${currencyInfo.id}"),
        currencyInfo: currencyInfo,
        selected: block.isCurrentItem(currencyInfo),
        onCurrencyPressed: _onCurrencyPressed,
      );
    },
  );
}
...
Handling the Reorder Event
When a user drops an item into a new position, the onReorder event is triggered. Here, we need to update the item's position within the Block's data list.
onReorder
void _onReorder(int oldIndex, int newIndex) {
  int newIdx = newIndex > oldIndex ? newIndex - 1 : newIndex;
  block.moveItemByIndexPosition(
    oldIndexPosition: oldIndex,
    newIndexPosition: newIdx,
  );
}
No ADS
No ADS