Search code examples
flutterdartmath

How to fix "The getter 'pi' was called on null" in Flutter Dart?


I'm encountering the following error in my Flutter Dart code:

The getter 'pi' was called on null. Receiver: null Tried calling: pi

I've tried the following, but they haven't resolved the issue:

  • Checking if pi is null
  • Using io instead of pi (importing dart:io didn't help)
  • Removing pi entirely

Relevant Code (with explanation):

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:math' as math;


// ... 

class CustomTimerPainter extends CustomPainter {
  // ... 

  @override
  void paint(Canvas canvas, Size size) {
    // ... existing code ...

    // Problem likely lies here:
    var math; // 'math' is never assigned a value
    double progress = (1.0 - animation.value) * 2 * math.pi; 
    canvas.drawArc(Offset.zero & size, math.pi * 1.5,
 -progress, false, paint);
  }  
} 

Explanation of the Issue:

I believe the error is caused by the math variable within the CustomTimerPainter. It's declared but never assigned a value, leading to a null reference when you try to use math.pi.

How can I fix this issue?


Solution

  • The issue is with this line

        var math;
    

    You have defined a variable called math, but haven't assigned it to anything. Since math is null, you get the error 'the getter 'pi' was called on null'.

    You need to delete this line.

    Your code will now work if you do

    import 'dart:math' as math;
    

    However, the math prefix is not necessary, so you could also do

    import 'dart:math;
    

    And use pi, instead of math.pi