79816826

Date: 2025-11-11 15:35:17
Score: 1
Natty:
Report link

After some researching, I found the example https://api.flutter.dev/flutter/widgets/BuildOwner-class.html#widgets.BuildOwner.1.

With it, I am able to calculate the width that the ReorderableListView should have, as follows:

import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';

Size measureWidget(Widget widget) {
    final pipelineOwner = PipelineOwner();
    final rootView = pipelineOwner.rootNode = MeasurementView();
    final buildOwner = BuildOwner(focusManager: FocusManager());
    final element = RenderObjectToWidgetAdapter<RenderBox>(
        container: rootView,
        debugShortDescription: '[root]',
        child: widget,
    ).attachToRenderTree(buildOwner);
    try {
        rootView.scheduleInitialLayout();
        pipelineOwner.flushLayout();
        return rootView.size;
    } finally {
        element.update(RenderObjectToWidgetAdapter<RenderBox>(container: rootView));
        buildOwner.finalizeTree();
    }
}

class MeasurementView extends RenderBox with RenderObjectWithChildMixin<RenderBox> {
    @override
    void performLayout() {
        assert(child != null);
        child!.layout(const BoxContraints(), parentUsesSize: true);
        size = child!.size;
    }

    @override
    void debugAssertDoesMeetContraints() => true;
}
Card.outlined(
    margin: const EdgeInsets.all(8),
    child: LayoutBuilder(
        builder: (context, contraints) {
            final itemPrototypeSize = measureWidget(
                Directionality(child: listItemPrototype, textDirection: Directionality.of(context)),
            );
            return SizedBox(
                width: itemPrototypeSize.width,
                child: ReorderableListView.builder(
                    itemCount: _objects.length,
                    buildDefaultDragHandles: false,
                    prototypeItem: listItemPrototype,
                    itemBuilder: (context, index) => _buildListItem(
                        context: context,
                        key: ValueKey(index),
                        index: index,
                        objectType: _objects[index],
                    ),
                    onReorder: (oldIndex, newIndex) {
                        final insertionIndex = (oldIndex < newIndex ? newIndex - 1 : newIndex);
                        final object = _objects.removeAt(oldIndex);
                        _objects.insert(insertionIndex, object);
                        setState(() {});
                    },
                ),
            );
        },
    ),
),
Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: user31112632