skip to Main Content

I am new to flutter but am doing my final year project of my degree. Am currently facing an issue with code to integrate google maps into my app.

void _addMarker(LatLng pos) {
  var _origin;
 ** if (_origin == null || (_origin != null && _destination != null))** {
    setState( () {
      _origin = Marker(
        markerId: const markerId('origin'),
        infoWindow: const InfoWindow(title: 'origin'),
        icon: 
            BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueGreen),
        position: pos,);
    });
  } else {}

I can get issue at _origin == null. It says the operand cant be null. Please help me with this issue.

2

Answers


  1. var _origin;
    

    You are checking the value of that variable, which of course is null.

    And dart analyzer is warning you, that variable can’t be null but it’s currently null which leading to make that condition always true.

    To FIX

    You have two options

    • assign a value to that variable before checking

    doesn’t make sense to check a variable while you are sure it has a
    value

    • Remove it from that condition

    Since you are sure it’s null now, so what’s the purpose of checking.

    I suggest the second option.

    btw, I’m keep thinking you are intending to check the value of another variable which has the same name of _origin. just recheck.

    Hope it helps you.

    Login or Signup to reply.
  2. I think you should declare _origin as a class-level variable, and you can declare it like , Marker? _origin;
    and the function can be like that :

    Marker? _origin;
    
    void _addMarker(LatLng pos) {
    if (_origin == null) {
    setState(() {
      _origin = Marker(
        markerId: const MarkerId('origin'),
        infoWindow: const InfoWindow(title: 'origin'),
        icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueGreen),
        position: pos,
      );
    });
    } else {}
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search