9

有没有办法Widget在 a 的给定位置绘制 a Canvas

更具体地说,我想在实际小部件前面单独绘制Marker与 a 相关的子小部件。这是创建一个可以做到这一点的尝试,但我无法弄清楚如何在画布上实际绘制小部件。使用requires a ,我不知道如何创建/检索:FlutterMapCanvasFlutterMapCustomPainterRenderObjectPaintingContext

class MarkerPainter extends CustomPainter {
  MapController mc;
  BuildContext context;
  List<Marker> markers;

  MarkerPainter(this.context, this.mc, this.markers);

  @override
  void paint(Canvas canvas, Size size) {
    if( markers != null && markers.isNotEmpty ){
      for(int i=0; i<markers.length; i++){
        Marker marker = markers[i];
        Offset o = myCalculateOffsetFromLatLng(marker.point, mc, context);

        // Won't work, this needs a PaintingContext...
        marker.builder(context).createElement().renderObject.paint(context, o); 
      }
    }
  }

  @override
  bool shouldRepaint(MarkerPainter oldDelegate) => oldDelegate.markers != markers;
}
4

1 回答 1

8

您不能使用CustomPainter执行此操作。

此类只是实际交易的简化:RenderObject,它可以访问与画家(和布局+更多)相关的所有内容。

你应该做的是,而不是CustomPainter,创建一个RenderBox(一个 2d RenderObject

在您的情况下,您想要的是绘制一个小部件列表。在这种情况下,您将需要创建:

总结一下,以这种方式使用的小部件:

MyExample(
  children: [
    Text('foo'),
    Text('bar'),
  ],
),

会这样写:

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

class MyExample extends MultiChildRenderObjectWidget {
  MyExample({
    Key? key,
    required List<Widget> children,
  }) : super(key: key, children: children);

  @override
  RenderMyExample createRenderObject(BuildContext context) {
    return RenderMyExample();
  }
}

class MyExampleParentData extends ContainerBoxParentData<RenderBox> {}

class RenderMyExample extends RenderBox
    with ContainerRenderObjectMixin<RenderBox, MyExampleParentData> {
  @override
  void setupParentData(RenderObject child) {
    if (child.parentData is! MyExampleParentData) {
      child.parentData = MyExampleParentData();
    }
  }

  @override
  void performLayout() {
    size = constraints.biggest;

    for (var child = firstChild; child != null; child = childAfter(child)) {
      child.layout(
        // limit children to a max height of 50
        constraints.copyWith(maxHeight: 50),
      );
    }
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    // Paints all children in order vertically, separated by 50px

    var verticalOffset = .0;
    for (var child = firstChild; child != null; child = childAfter(child)) {
      context.paintChild(child, offset + Offset(0, verticalOffset));

      verticalOffset += 50;
    }
  }
}
于 2020-05-18T09:49:02.850 回答