Reputation: 147
My goal is to draw a line, however, it is not working. I find out that the size parameter in paint function is always 0 why ? what should I change in order to make it works
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)),
);
Upvotes: 1
Views: 355
Reputation: 54365
You can copy paste run full code beow
Step 1 : You can wrap with Container
to provide size
Step 2 : You need path.close()
and canvas.drawPath()
Step 3 : CurvePainter
typo need CurvePainter()
, you loss ()
code snippet
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())))
working demo
full code
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()))),
);
}
}
Upvotes: 1