How to return a bool value from aync/await function and pass it to other variable in other page - flutter

I want check if device is connected to internet or not and i done with class that do this work and return to me a bool value and i use from this class to other page and pass returned value to bool variable but get get this error that say Future<dynamic> is not a subtype of type bool in type cast
import 'dart:io';
class CheckConnection{
static Future<bool> checkConnection() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return (await checkConnection()) == true;
}
} on SocketException catch (_) {
print('not connected');
}
}
}

In place where you want to check you have to do like this:
CheckConnection.checkConnection().then((bool result){
/* check result here */
})
Or you can do this inside async function like checkConnection:
void _myFunction() async {
bool result = await CheckConnection.checkConnection();
/* check result here */
}

I don't get why you call checkConnection again inside for it (recursive effect). Are you sure you don't want to do like:
class CheckConnection {
static Future<bool> checkConnection() async {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return true;
}
/* try catch also can be applied! */
return false;
}
}

Just return this
return await checkConnection();

Related

Flutter/Dart convert future bool to bool

Can some one help me to identify the issue in below piece of code
void main() async {
bool c =getstatus();
print(c);
}
Future<bool> getMockData() {
return Future.value(false);
}
bool getstatus() async
{
Future<bool> stringFuture = getMockData();
bool message = stringFuture;
return(message); // will print one on console.
}
To get values from a Future(async) method, you have to await them. And after await the variable you get is not a Future anymore. So basically your code should look like this:
void main() async {
bool c = await getstatus();
print(c);
}
Future<bool> getMockData() {
return Future.value(false);
}
Future<bool> getstatus() async {
bool message = await getMockData();
return message;
}
Future<bool> stringFuture = await getMockData();
an async method must return Future of something then in the main you have to get the bool value by writing await
void main() async {
bool c = await getstatus();
print(c); // will print false on the console.
}
Future<bool> getMockData() {
return Future.value(false);
}
Future<bool> getstatus() async {
Future<bool> stringFuture = await getMockData();
return stringFuture; // will return false.
}

Flutter Firestore Query snapshot- result is always null

I have a simple flutter code to retrieve some data from Firestore. the data is retireved correctly, however passing the data from the future function making the result always null. can you advise how to adapt the code to return the list?
that is the class where the actual query is happening:
class DatabaseManager {
final CollectionReference BusinessProfilesCollection =
FirebaseFirestore.instance.collection("BusinessProfilesCollection");
Future GetBusinessProfilesCollection() async {
List businessprofileslist = [];
try {
await BusinessProfilesCollection.get().then((QuerySnapshot) {
QuerySnapshot.docs.forEach((element) {
businessprofileslist.add(element.data());
print(businessprofileslist[0]);
});
});
} catch (e) {
print(e.toString());
return null;
}
}
}
here is the page where I am calling the function: (however the result is always null)
class _ProfilesListPageState extends State<ProfilesListPage> {
List businessprofileslist = [];
#override
void initState() {
super.initState();
fetchBusinessProfilesList();
}
fetchBusinessProfilesList() async {
dynamic result = await DatabaseManager().GetBusinessProfilesCollection();
print(result.toString());
if (result == null) {
print('enable to retieve');
} else {
print('success');
setState(() {
businessprofileslist = result;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold();
}
}
You're not returning anything from GetBusinessProfilesCollection but null, so the result seems somewhat expected.
I guess you want to do:
class DatabaseManager {
final CollectionReference BusinessProfilesCollection =
FirebaseFirestore.instance.collection("BusinessProfilesCollection");
Future GetBusinessProfilesCollection() async {
List businessprofileslist = [];
try {
var QuerySnapshot = await BusinessProfilesCollection.get();
querySnapshot.docs.forEach((element) {
businessprofileslist.add(element.data());
});
return businessprofileslist;
} catch (e) {
print(e.toString());
return null;
}
}
}
Btw: returning null when the load fails, is just going to lead to a null pointer exception when you then do print(result.toString());. So I recommend not catching the error and just letting it bubble up. With that your code can be simplified to:
class DatabaseManager {
final CollectionReference BusinessProfilesCollection =
FirebaseFirestore.instance.collection("BusinessProfilesCollection");
Future GetBusinessProfilesCollection() async {
var QuerySnapshot = await BusinessProfilesCollection.get();
return querySnapshot.docs.map((element) => element.data());
}
}
You just need to return the list
return businessprofileslist;
CODE :
class DatabaseManager {
final CollectionReference BusinessProfilesCollection =
FirebaseFirestore.instance.collection("BusinessProfilesCollection");
Future GetBusinessProfilesCollection() async {
List businessprofileslist = [];
try {
await BusinessProfilesCollection.get().then((QuerySnapshot) {
QuerySnapshot.docs.forEach((element) {
businessprofileslist.add(element.data());
print(businessprofileslist[0]);
});
// you just need to return the list here after filling it up
return businessprofileslist;
});
} catch (e) {
print(e.toString());
return null;
}
}
}
Code with a little improvement:
class DatabaseManager {
final CollectionReference BusinessProfilesCollection =
FirebaseFirestore.instance.collection("BusinessProfilesCollection");
Future GetBusinessProfilesCollection() async {
await BusinessProfilesCollection.get().then((QuerySnapshot) {
QuerySnapshot.docs.map((doc) => doc.data()).toList();
});
}
}
Try that with calling the function in feching
fetchBusinessProfilesList()
async {
dynamic result ;
await DatabaseManager().GetBusinessProfilesCollection().then((value){
result=value;
print(result.toString());
if (result == null) {
print('enable to retieve');
} else {
print('success');
setState(() {
businessprofileslist = result;
});
}
});
}

Null check operator used on a null value- futter chat

I'm creating a chat app with sending voice message. now I'm getting this error in my code. appreciate your help on this. I HAVE INSERTED FOLLOWING CODE ANS THEN ERROR APPEARS. Cant find a exact file error occurring.
Null check operator used on a null value
class SoundRecorder {
FlutterSoundRecorder? _audioRecorder;
bool _isRecorderInitialised = false;
bool get isRecording => _audioRecorder!.isRecording;
Future init() async {
_audioRecorder = FlutterSoundRecorder();
await _audioRecorder?.openAudioSession(); //start recording
//asking permisson
final status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
throw RecordingPermissionException("Microphone permission");
}
await _audioRecorder!.openAudioSession();
_isRecorderInitialised = true;
}
void dispose() {
if (!_isRecorderInitialised) return;
_audioRecorder!.closeAudioSession();
_audioRecorder = null;
_isRecorderInitialised = false;
}
Future _record() async {
if (!_isRecorderInitialised) return;
await _audioRecorder!.startRecorder(toFile: pathToSaveAudio);
}
Future _stop() async {
if (!_isRecorderInitialised) return;
await _audioRecorder!.stopRecorder();
}
Future toggleRecording() async {
if (_audioRecorder!.isStopped) {
await _record();
} else {
await _stop();
}
}
}
Looks like at some point you use the ! operator to assert that _audioRecorder isn't null but it actually is. From the stack, I think this would be from the isRecording getter.
A simple fix to this would be to make the getter bool get isRecording => _audioRecorder?.isRecording ?? false, since if _audioRecorder is null, then you can't be recording, right?

dart future method with bool return type always returns false

I am calling class method which is in a different file from the main method of main.dart. Here I am trying to get the session status of the user. I am not sure what I am doing wrong, the return value always returns false when called in from the main method, but returns true if printed out in the actual method.
Here the expected result is true as the user is currently in the system and is signed in.
Here is my main method -
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await Authenticate().getSessionStatus().then((status) => {
print(status)
});
}
Here is my class method -
class Authenticate {
Future<bool> getSessionStatus() async {
bool _isSessionActive = false;
await FirebaseAuth.instance.authStateChanges().listen((User? user) {
if (user == null) {
//print('User is currently signed out!');
_isSessionActive = false;
} else {
//print('User is signed in!');
_isSessionActive = true;
}
});
return _isSessionActive;
}
}
The print statements inside the Authenticate class method, if turned on returns true which is the expected value, but calling the getSessionStatus method from the main method and then printing the value of the status variable always returns false. I believe it has something to do with order in which it is processed, but I am not able to fix it at all.
You can't check if the user is logged with FirebaseAuth.instance.authStateChanges(), since this method only notifies when the user status changes.
You can use the FirebaseAuth.instance.currentUser property instead:
class Authenticate {
Future<bool> getSessionStatus() async {
return FirebaseAuth.instance?.currentUser != null;
}
}
You cannot await the StreamSubscription (which the compiler should warn you about) returned by FirebaseAuth.instance.authStateChanges().listen(...). Below is a minimal example to illustrate what is happening.
void main() async {
bool test = await awaitMe();
print('Main received:' + test.toString());
}
Future<bool> awaitMe() async {
bool innerVal = false;
print('start');
await streamMe().listen((val) {
print('Listener received: ' + val.toString());
innerVal = true;
});
print('end');
return innerVal;
}
Stream<bool> streamMe () async* {
yield true;
}
This will print:
start
end
Main received:false
Listener received: true
So you are actually not awaiting anything.

How to convert Future<bool> into Stream<bool>

In my Flutter app, I have a function returning Future, but I wanna get result as Stream. Here is the function :
Future<bool> isGpsOn() async {
if (await Geolocator().isLocationServiceEnabled()) {
return true;
} else {
return false;
}
}
How to do that?
Read the manual and check my answer:
Stream<bool> gpsStatusStream() async* {
bool enabled;
while (true) {
try {
bool isEnabled = await Geolocator().isLocationServiceEnabled();
if (enabled != isEnabled) {
enabled = isEnabled;
yield enabled;
}
}
catch (error) {}
await Future.delayed(Duration(seconds: 5));
}
}
gpsStatusStream().listen((enabled) {
print(enabled ? 'enabled' : 'disabled');
});
or create convertor:
Stream futureToStream(fn, defaultValue, Duration duration) async* {
var result;
while (true) {
try {
result = await fn();
}
catch (error) {
result = defaultValue;
}
finally {
yield result;
}
await Future.delayed(duration);
}
}
Future<bool> isGpsOn() async {
return await Geolocator().isLocationServiceEnabled();
}
final gpsStatusStream = futureToStream(isGpsOn, false, Duration(seconds: 5));
gpsStatusStream.listen((enabled) {
print(enabled ? 'enabled' : 'disabled');
});
If you don't want to change the return type of your function, you could make callers convert the Future<T> to a Stream<T> by simply calling asStream() on the returned Future.