skip to Main Content

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:

Result

2

Answers


  1. You are using nullable dataType List<Color>? colors;, So it is possible to get null.

    You can pass empty list on null case

        List<Color> gradColors = colors
                ?.map(
                  (color) => color.withOpacity(
                    Random().nextDouble().clamp(0.5, 0.9),
                  ),
                )
                .toList() ??
            [];
    
    Login or Signup to reply.
  2. You can use Yeasin Sheikh‘s answer, but here are two more ways:

    List<Color> gradColors = colors == null ? [] : colors!.map((color) => color.withOpacity(Random().nextDouble().clamp(0.5, 0.9))).toList();
    

    or

    List<Color> gradColors = (colors ?? []).map((color) => color.withOpacity(Random().nextDouble().clamp(0.5, 0.9))).toList();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search