轻按按钮时如何在容器上画线

时间:2019-05-03 15:48:46

标签: android dart flutter

我仍在学习Flutter,还没有完全了解CustomPainter。

以下代码未在嵌套在Column中的Container上绘制线。我想在点击“绘制线条”按钮时绘制线条。

在调试代码时,我可以看到调用了CustomPainter,但未画线。

import 'package:flutter/material.dart';
void main() {
  runApp(
    MaterialApp(
      home: Home(),
    ),
  );
}
class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomeState();
  }
}
class _HomeState extends State<Home> {
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text('Draw Line'),
      ),
      backgroundColor: Colors.white,
      body: Column(
        children: <Widget>[
          SizedBox(
            height: 200,
            width: 200,
            child: Container(),
          ),
          RaisedButton(
            onPressed: () {
              CustomPaint(
                painter: LinePainter(),
              );
            },
            child: Text('Draw Line'),
          )
        ],
      ),
    );
  }
}
class LinePainter extends CustomPainter {
  Paint _paint;
  LinePainter() {
    _paint = Paint()
      ..color = Colors.amber
      ..strokeWidth = 8.0;
  }
  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawLine(Offset(0.0, 0.0), Offset(size.width, size.height), _paint);
  }
  @override
  bool shouldRepaint(LinePainter oldDelegate) {
    return true;
  }
}

1 个答案:

答案 0 :(得分:1)

您的窗口小部件层次结构顺序错误。您需要使用CustomPainter作为父窗口小部件。我还实现了一个简单的逻辑,将第二点作为Offset传递给画家。您还可以根据需要传递一个简单的boolean变量来控制“已绘制”和“干净”状态。

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Home(),
    ),
  );
}

class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomeState();
  }
}

class _HomeState extends State<Home> {
  Offset _offset = Offset(0, 0);

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text('Draw Line'),
      ),
      backgroundColor: Colors.white,
      body: Column(
        children: <Widget>[
          SizedBox(
            height: 200,
            width: 200,
            child: Container(),
          ),
          CustomPaint(
            foregroundPainter: LinePainter(_offset),
            child: RaisedButton(
              onPressed: () {setState(() {
                _offset = Offset(60, 60);
              });},
              child: Text("Draw Line"),
            ),
          )
        ],
      ),
    );
  }
}

class LinePainter extends CustomPainter {
  Paint _paint;
  Offset _offset;

  LinePainter(Offset offset) {
    _offset = offset;
    _paint = Paint()
      ..color = Colors.amber
      ..strokeWidth = 8.0;
  }

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawLine(Offset(0, 0), _offset, _paint);
  }

  @override
  bool shouldRepaint(LinePainter oldDelegate) {
    return true;
  }
}