Search code examples
flutterdartcustom-painter

Get the height of a widget in a List


I'm working on a CustomPainter widget that receives a List<Widget> as an argument. I would like to know the size of each of my Widget so I can adjust my paint. The List<Widget> will be a user-selected List so I can't use GlobalKeys here.

I watched some answers on StackOverflow and articles on the subject but every time the answer seems not adapted to my problem.

class MyPainter extends CustomPainter {
  final List<Widget> myWidgetList;

  MyPainter({
    this.myWidgetList,
  });

  @override
  void paint(Canvas canvas, Size size) {

    for (var item in myWidgetList) {
      // print my widget height.
    }
    ...
  }
}

Solution

  • Since I couldn't get the size of my widget before the rendering, I wrapped every widget in my List<Widget> into another widget that will use GlobalKey and then get access to the size of each of my widget with Context.

    It's not a perfect solution but it's the best I could find so far.

    class SubtaskWrapper extends StatelessWidget {
      final Widget child;
      final Function onChange;
      final SubTasksViewModel model;
    
      SubtaskWrapper({
        Key? key,
        required this.onChange,
        required this.model,
        required this.child,
      }) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        SchedulerBinding.instance!.addPostFrameCallback(postFrameCallback);
    
        return Container(
          key: widgetKey,
          child: child,
        );
      }
    
      GlobalKey widgetKey = GlobalKey();
      Size? oldSize;
    
      void postFrameCallback(_) {
        BuildContext? context = widgetKey.currentContext;
        if (context == null) return;
    
        Size? newSize = context.size;
        if (oldSize == newSize) return;
    
        oldSize = newSize;
        onChange(newSize, model);
      }
    }