Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't figure out this Error "The method 'map' can't be unconditionally invoked because the receiver can be 'null'"

I’m following this speed code tutorial(https://www.youtube.com/watch?v=KO_PYJKHglo) 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

result

>Solution :

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() ??
        [];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading