用脚手架小部件画一条线

时间:2020-02-20 23:36:52

标签: flutter

我的目标是画一条线,但是它没有用。 我发现画图功能中的size参数始终为0 为什么呢?我应该进行哪些更改才能使其正常工作

class CurvePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
  var paint = Paint();
  paint.color = Colors.green[800];
  paint.style = PaintingStyle.stroke;
  paint.strokeWidth = 2.0;
  var path = Path();
  path.lineTo(size.width, size.height);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
  return true;
}
}
class Home extends StatelessWidget{
@override
Widget build(BuildContext context){
  return Scaffold(
    appBar: AppBar(
      title: Text('Test'),
    ),
    body: Center(child: CustomPaint(painter: CurvePainter)),
  );

1 个答案:

答案 0 :(得分:1)

您可以复制粘贴运行完整的代码,如下所示
步骤1:您可以用Container包装以提供尺寸
步骤2:您需要path.close()canvas.drawPath()
步骤3:CurvePainter的错字需要CurvePainter(),您损失了()

代码段

void paint(Canvas canvas, Size size) {
    var paint = Paint();
    paint.color = Colors.green[800];
    paint.style = PaintingStyle.stroke;
    paint.strokeWidth = 2.0;
    var path = Path();

    print(size.height);
    path.lineTo(size.width, size.height);
    path.close();
    canvas.drawPath(path, paint);
  }
...
body: Center(
          child: Container(
              width: 100,
              height: 100,
              child: CustomPaint(painter: CurvePainter())))

工作演示

enter image description here

完整代码

import 'package:flutter/material.dart';

class CurvePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint();
    paint.color = Colors.green[800];
    paint.style = PaintingStyle.stroke;
    paint.strokeWidth = 2.0;
    var path = Path();

    print(size.height);
    path.lineTo(size.width, size.height);
    path.close();
    canvas.drawPath(path, paint);
  }

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

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

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

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Test'),
      ),
      body: Center(
          child: Container(
              width: 100,
              height: 100,
              child: CustomPaint(painter: CurvePainter()))),
    );
  }
}