The getter 'value' isn't defined for the type BehaviorSubject<>

1.8k Views Asked by At

After I updated the code to adapt flutter null safety the code below gaves me the error

The getter 'value' isn't defined for the type 'BehaviorSubject'.

final _brightness = BehaviorSubject<Brightness>();
...
if (_brightness.value == Brightness.light) { ... } // error is here

How to get value from BehaviorSubject then?

Using rxdart: ^0.26.0

2

There are 2 best solutions below

0
On

This is because the value getter is not implemented by BehaviorSubject class this function belongs to ValueStreamExtensions file which itself is an extension method file on the ValueStream class which BehaviorSubject is implemented by if you wish to use extension function of any type in your code you should first import the extension file into to your code file in this case just add

import 'package:rxdart/src/streams/value_stream.dart';

also, note that for using the BehaviorSubject class your should import that too

import 'package:rxdart/src/subjects/behavior_subject.dart';

or directly import the main Rx library file which imports other dependencies you may wanna use in your code like this " This is the recommended way "

import 'package:rxdart/rxdart.dart';

also, BehaviorSubject itself has a getter which is called valueWrapper that holds the latest value of your subject and you can directly use this getter

here is more information about extension methods in dart https://dart.dev/guides/language/extension-methods

0
On

The Code you provided reads like you want to get the value from a Brightness Instance which is stored in the BehaviorSubject.

https://pub.dev/documentation/rxdart/latest/rx/BehaviorSubject-class.html

A special StreamController that captures the latest item that has been added to the controller, and emits that as the first item to any new listener.

Your _brightness variable is not from type Brightness its of type BehaviorSubject. So you have to subscribe with a listener to it and you will get the latest value which has been added to the BehaviorSubject.