I’m following this speed code tutorial and I’m facing some problems during somewhere on 5:08.
import 'package:flutter/material.dart';
import 'dart:math';
class WaveColorPainter extends CustomPainter {
Paint? _paint;
List<Color>? colors;
@override
void paint(Canvas canvas, Size size) {
colors = List.from(Colors.accents);
colors!.removeRange(6, 13); //null safety
List<Color> gradColors = colors.map(
(color) => color.withOpacity(
Random().nextDouble().clamp(0.5, 0.9),
),
);
final Gradient gradient = LinearGradient(colors: gradColors);
_paint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1.5
..shader = gradient.createShader(
Rect.fromLTWH(
0,
20,
size.width,
40,
),
);
canvas.translate(0, size.height / 2);
canvas.scale(1, -1);
for (int i = 0; i < size.width.toInt(); i++) {
double x = i.toDouble();
double r = 2 * sin(i) - 2 * cos(4 * i) + sin(2 * i - pi * 24);
r = r * 5;
canvas.drawLine(Offset(x, r), Offset(x, -r), _paint!);
} // frequency bar
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
}
Up above is my code and I tried both ?
and !
on every variables and functions but I can’t figure out what the problem is.
And this is how my vscode looks right now:
2
Answers
You are using nullable dataType
List<Color>? colors;
, So it is possible to get null.You can pass empty list on null case
You can use Yeasin Sheikh‘s answer, but here are two more ways:
or