Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A nullable expression can't be used as a condition

I am getting a "nullable expression" error. The problem is occurring in the following lines:

left: isSideBarOpenedAsync.data ? 0 : 0,
right: isSideBarOpenedAsync.data ? 0 : screenWidth - 35,

Where isSideBarOpenedAsync is type AsyncSnapshot<bool>

This is the error I'm getting

A nullable expression can't be used as a condition. Try checking that the value isn't null before using it as a condition.

Here's the full code for reference

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:solaris/constants.dart';
import 'package:rxdart/rxdart.dart';

class SideBar extends StatefulWidget {

  @override
  _SideBarState createState() => _SideBarState();
}

class _SideBarState extends State<SideBar> with SingleTickerProviderStateMixin<SideBar>{
  late AnimationController _animationController;
  late StreamController<bool> isSidebarOpenedStreamController;
  late Stream<bool> isSideBarOpenedStream;
  late StreamSink<bool> isSideBarOpenedSink;
  final _animationDuration = const Duration(milliseconds: 500);

  @override
  void initState(){
    super.initState();
    _animationController = AnimationController(vsync: this, duration: _animationDuration);
    isSidebarOpenedStreamController = PublishSubject<bool>();
    isSideBarOpenedStream = isSidebarOpenedStreamController.stream;
    isSideBarOpenedSink = isSidebarOpenedStreamController.sink;
  }
  @override
  void dispose(){
  _animationController.dispose();
  isSidebarOpenedStreamController.close();
  isSideBarOpenedSink.close();
  super.dispose();
  }

  void onIconPressed(){
    final animationStatus = _animationController.status;
    final isAnimationCompleted = animationStatus == AnimationStatus.completed;

    if(isAnimationCompleted){
      isSideBarOpenedSink.add(false);
      _animationController.reverse();
    }else{
      isSideBarOpenedSink.add(true);
      _animationController.forward();
    }
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;

    return StreamBuilder<bool>(
      initialData: false,
      stream: isSideBarOpenedStream,
      builder: (context, isSideBarOpenedAsync){
        return AnimatedPositioned(
          duration: _animationDuration,
          top: 0,
          bottom: 0,
          left: isSideBarOpenedAsync.data ? 0 : 0,
          right: isSideBarOpenedAsync.data ? 0 : screenWidth - 35,
          child: Row(
            children: <Widget>[
              Expanded(
                child: Container(
                  color: red,
                ),
              ),
              Align(
                alignment: Alignment(0,-0.9),
                child: GestureDetector(
                  onTap: (){
                    onIconPressed();
                  },
                  child: Container(
                    width: 35,
                    height: 110,
                    color: blue,
                    alignment: Alignment.centerLeft,
                    child: AnimatedIcon(
                      progress: _animationController.view,
                      icon: AnimatedIcons.menu_close,
                      color: white,
                      size: 25,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
like image 993
Tμrf Avatar asked May 28 '21 13:05

Tμrf


People also ask

What is null safety in Dart?

Null safety prevents errors that result from unintentional access of variables set to null . For example, if a method expects an integer but receives null , your app causes a runtime error. This type of error, a null dereference error, can be difficult to debug.

Why is null safety important?

September 28, 2021. Null safety means that a variable cannot have a null or void value. This feature improves user satisfaction by reducing errors and app crashes. Null safety ensures that all runtime null-dereference problems are shown at compile-time.

What is late keyword in Dart?

In Dart, we use the late keyword to declare variables that will be initialized later. These are called non-nullable variables as they are initialized after the declaration. Hence, we use the late keyword. Note: Once we declare a non-nullable late variable, the variable can't be null at runtime.

Can I use a nullable expression as a bool value?

Yes, "nullable" is fine, as is "non-nullable" and "potentially nullable". "A nullable expression cannot be used as a bool value." "Try checking that the value isn't 'null' before using it as a bool value."

Can a nullable expression be used as an iterator?

message: "A nullable expression cannot be used as an iterator." correction: "Try checking that the value isn't 'null' before using it as an iterator." message: "A nullable expression cannot be used in a spread." correction: "Try checking that the value isn't 'null' before using it in a spread, or use a null-aware spread."

What happens if a nullable expression is dereferenced?

If a nullable expression is "dereferenced" (e.g. int? x; x.isEven; ), the analyzer reports the following error: An expression whose value can be 'null' must be null-checked before it can be dereferenced.

Can a nullable expression be used in a for-in loop?

message: "A nullable expression can't be used as an iterator in a for-in loop." "An expression whose value can be 'null' must be null-checked before an operator can be invoked."


Video Answer


2 Answers

If you know that isSideBarOpenedAsync.data will always have a value, you can use a ! to force the value to not be null.

isSideBarOpenedAsync.data!

This changes the value's type from bool? to bool.
Your ternary expressions will work with this logic.

Note: if isSideBarOpenedAsync.data is null using a ! will throw an error, bool cannot be type null.

Alternatively, you can provide a value to be used if the value is null

(isSideBarOpenedAsync.data ?? false)

If isSideBarOpenedAsync.data has a non-null value, it will be referenced. If the value is null, false will be used instead.

like image 180
mrgnhnt96 Avatar answered Oct 19 '22 14:10

mrgnhnt96


For more clarification about null safety issue just sharing some info here

There has 3 ways to handle null :

1. ?. Operator - value is Null or not by using simple syntax.

data?.varibale;

2. ?? Operator - has Null value and we can also pass default value like

variable ?? "";
    

3. ??= Operator - variable is Null or not. If the variable is Null then it will assign a new value to it

int x = 5;
x ??= 2;
    

Note : I have solved my same issue using ?. operator against bang(!)

May it help someone. Thanks

like image 1
Mimu Saha Tishan Avatar answered Oct 19 '22 14:10

Mimu Saha Tishan