使用CustomPainter时小部件的污点

时间:2020-04-20 03:41:17

标签: flutter

当我尝试使用使用CustomPainter()来绘制ListView.builder()内的形状的自定义Widget时遇到问题。

我遇到的问题是,当我滚动浏览包含这些小部件的列表时,它们似乎“涂抹”了它们绘制的区域...。

最好看一下这些图片: 这些是滚动之前的ListView ... Before Scrolling 这些是在我向左滚动一点之后。 After Scrolling 这是在我一直向左滚动之后。 After Full scroll

如您所见,滚动列表视图时,小部件似乎会弄脏自己?

我认为滚动项目时需要重新绘制列表视图... 我尝试将shouldRepaint()方法从false更改为true,但没有任何效果...

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: TextOnCanvasList(),
    );
  }
}

class TextOnCanvasList extends StatelessWidget {
  final List<String> listOfNames = ["Matt","John","Bill","Doug","Paul","Hanz","Ruby","Karl"];
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        reverse: false,
        itemBuilder: (_, int index) => TextOnCanvasWidget(this.listOfNames[index]),
        itemCount: listOfNames.length,
      ),
    );
  }
}

class TextOnCanvasWidget extends StatelessWidget {
  final String  name;
  TextOnCanvasWidget(this.name);
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        new CustomPaint(
          size: Size(65, 20),
          foregroundPainter: new TextOnCanvasPainter(this.name),
        ),
      ],
    );
  }
}

class TextOnCanvasPainter extends CustomPainter {
  final String name;
  TextOnCanvasPainter(this.name);
  static const l0 = 50.0;
  static final l1 = 10.0;
  static final h = 30.0;
  final Path chevron = new Path()
    ..relativeLineTo(l0, 0)
    ..relativeLineTo(0, h )
    ..relativeLineTo(-l0, 0)
    ..relativeLineTo(0, -h )
    ..close();
  void paint(Canvas canvas, Size size) {
    Paint fillShape = new Paint()
      ..color = Colors.blue
      ..style = PaintingStyle.fill
      ..strokeWidth = 2.0;
    TextSpan span = new TextSpan(
      style: new TextStyle(color: Colors.red[600]),
      text: this.name,
    );
    TextPainter tp = new TextPainter(
        text: span,
        textAlign: TextAlign.left,
        textDirection: TextDirection.ltr);
    tp.layout(minWidth: 500.0);
    canvas.drawPath(chevron, fillShape);
    tp.paint(canvas, new Offset(l1, h / 8));
    canvas.save();
    canvas.restore();
  }
  @override
  bool shouldRepaint(TextOnCanvasPainter oldDelegate) => true;
}

有什么想法吗?

0 个答案:

没有答案