skip to Main Content

I want to paint Widget in a RenderBox derivative. I tried the obvious, but no painting occured. What am I doing wrong?

Ive got a vague feeling that I should subclass RenderObjectWidget and do some sort of a Element, but I’d rather shortcut that

import 'package:flutter/material.dart';

void main() {
  runApp(const K());
}

class K extends LeafRenderObjectWidget {
  const K({super.key});

  @override
  RenderObject createRenderObject(BuildContext context) {

    const w = SizedBox.square(
      dimension: 30,child: ColoredBox(color: Colors.green),
    );
    final row = w.createRenderObject(context);
    row.layout(const BoxConstraints());

    return KImpl(row);
  }
}

class KImpl extends RenderBox {

  KImpl(this.ro);

  RenderObject ro ;

  @override
  void performLayout() {
    final c = constraints.normalize();
    size = Size(c.maxWidth, c.maxHeight);
  }
  @override
  void paint(PaintingContext context, Offset offset) {
    context.canvas.drawColor(Colors.red, BlendMode.src);

    context.paintChild(ro, Offset.zero); // THIS HAS NO EFFECT !
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    Seems like this is what I need


  2. Here’s an updated version of your code with a modification to the Offset passed to context.paintChild:

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(const K());
    }
    
    class K extends LeafRenderObjectWidget {
      const K({Key? key}) : super(key: key);
    
      @override
      RenderObject createRenderObject(BuildContext context) {
        const w = SizedBox.square(
          dimension: 30,
          child: ColoredBox(color: Colors.green),
        );
        final row = w.createRenderObject(context);
        row.layout(const BoxConstraints());
    
        return KImpl(row);
      }
    }
    
    class KImpl extends RenderBox {
      KImpl(this.ro);
    
      final RenderObject ro;
    
      @override
      void performLayout() {
        final c = constraints.normalize();
        size = Size(c.maxWidth, c.maxHeight);
      }
    
      @override
      void paint(PaintingContext context, Offset offset) {
        context.canvas.drawColor(Colors.red, BlendMode.src);
        
        // Adjust the offset based on your requirements
        final childOffset = Offset(10, 10);
        
        context.paintChild(ro, offset + childOffset);
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search