How to migrate List fold to null saftey


this code runs fine without null safety:

void main() {
  final a = X(22.5);
  final b = X(22.5);
  List<X> x = [a, b];
  var tot = x.fold(0.0, (a, b) => a + b.dist);

class X {
  final double dist;

with null safety we get:

The operator ‘+’ can’t be unconditionally invoked because the receiver can be ‘null’.
Try adding a null check to the target (‘!’).

No idea who/what the target is or the receiver for that matter. I’ve read all the Dart material on null safety and can’t get this to build as an arrow expression ( => a + b.dist).

Thanks for any help!


You can pick one of the approaches below:

  1. Define the fold method type parameter explicitly:
var tot = x.fold<double>(0.0, (a, b) => a + b.dist);
  1. Define the tot variable type explicitly:
double tot = x.fold(0.0, (a, b) => a + b.dist);

Answered By – enzo

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.