'RenderObject?' 类型的值不能分配给“RenderBox”类型的变量

时间:2021-06-16 04:46:03

标签: flutter dart

我正在尝试在颤振中构建一个非常简单的绘画应用程序。我得到了“'RenderObject 类型的值?'无法分配给“RenderBox”类型的变量。”错误。

我附上了下面的代码,错误在第 18 行(即在 RenderBox object = context.findRenderObject();)

import 'package:flutter/material.dart';

class drawPage extends StatefulWidget {
  @override
  _drawPageState createState() => new _drawPageState();
}

class _drawPageState extends State<drawPage> {
  List<Offset> _points = <Offset>[];

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(
        child: new GestureDetector(
          onPanUpdate: (DragUpdateDetails details) {
            setState(() {
              RenderBox object = context.findRenderObject();
              Offset _localPosition =
                  object.globalToLocal(details.globalPosition);
              _points = new List.from(_points)..add(_localPosition);
            });
          },
          onPanEnd: (DragEndDetails details) => _points.add(Offset.zero),
          child: new CustomPaint(
            painter: new Signature(points: _points),
            size: Size.infinite,
          ),
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.clear),
        onPressed: () => _points.clear(),
      ),
    );
  }
}

class Signature extends CustomPainter {
  List<Offset> points;

  Signature({this.points});

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = new Paint()
      ..color = Colors.blue
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 10.0;

    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != Offset.zero && points[i + 1] != Offset.zero) {
        canvas.drawLine(points[i], points[i + 1], paint);
      }
    }
  }

  @override
  bool shouldRepaint(Signature oldDelegate) => oldDelegate.points != points;
}

1 个答案:

答案 0 :(得分:1)

试试这个:

RenderBox object = context.findRenderObject() as RenderBox;

我们应该将泛型类型转换为确定类型,请参考 this official link