skip to Main Content

enter image description here

I’m trying to use a GridView.builder with dynamic height depending on the largest item in each row. A Wrap is not ok for this, because it renders all items at once. the builder is only rendering the visible items. I won’t calculate a childAspectRatio manually for each row.

Any ideas?

2

Answers


  1. I’ve made a WrapBuilder which sort of like a Wrap but uses a builder. The caveat though is that you need to know the width of the items beforehand. If that’s okay you can try using this class:

    import 'dart:math';
    import 'package:flutter/cupertino.dart';
    
    typedef ValueWidgetBuilder<T> = Widget Function(T value);
    
    class WrapBuilder extends StatelessWidget {
      final double itemWidth;
      final List items;
      final ValueWidgetBuilder itemBuilder;
    
      const WrapBuilder(
          {Key? key,
          required this.itemWidth,
          required this.items,
          required this.itemBuilder})
          : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return LayoutBuilder(builder: (context, constraints) {
          var itemsPerRow = max(1, constraints.maxWidth ~/ itemWidth);
          return ListView.builder(
                shrinkWrap: true,
                controller: ScrollController(),
                itemCount: (items.length / itemsPerRow).ceil(),
                itemBuilder: (BuildContext context, int index) {
                  var rowItems = items.sublist(itemsPerRow * index,
                      min(itemsPerRow * (index + 1), items.length));
                  return Row(children: [
                    for (final item in rowItems)
                      SizedBox(
                          width: itemWidth,
                          child: itemBuilder(item))
                  ]);
                },
              );
        });
      }
    }
    

    You might need to tweak it for your use case. In my case I have a list that is some data and the itemBuilder takes one of this data as parameter.

    Login or Signup to reply.
  2. you can pass height as variable in list and then set height for the row from list

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search