Flutter how to get a Future<bool> to a normal bool type - android

Hi I'm trying to get a Future to be used as a normal boolean, how do I use this function as the determiner for a normal boolean without it giving me an incorrect type error?
Future<bool> checkIfOnAnyChats() async {
FirebaseUser user = await _auth.currentUser();
final QuerySnapshot result = await _firestore
.collection('chats')
.where('members', arrayContains: _username)
.getDocuments();
final List<DocumentSnapshot> documents = result.documents;
if(documents.length > 0) {
return Future<bool>.value(true);
}else{
return Future<bool>.value(false);
}
}
How do I apply it to a normal type boolean and not get this error? Thanks.

you don't need to convert bool into future, as you are in async method it will return future only.
you can get that value in initstate, you can not get value outside any method.
bool _isInChat;
#override
void initState() {
super.initState();
CheckIfOnAnyChats().then((value){
SetState((){
_isInChat = value;
});
});
}

Related

'setup' is deprecated and shouldn't be used. Use PurchasesConfiguration

How can i fix this and make it not deprecated
import 'package:purchases_flutter/purchases_flutter.dart';
class PurchaseApi{
static const _apiKey = '';
static Future init() async{
await Purchases.setDebugLogsEnabled(true);
await Purchases.setup(_apiKey);
}
static Future<List<Offering>> fetchOffers() async {
try{
final offerings = await Purchases.getOfferings();
final current = offerings.current;
return current == null ? [] : [current];
} on PlatformException catch (e) {
return [];
}
}
}
I already changed the firt on to await Purchases.setLogLevel(true as LogLevel); But when i change the setup one i get an error. The error is The method 'PurchasesConfiguration' isn't defined for the type 'Purchases'. I already tried to import'package:purchases_flutter/models/purchases_configuration.dart';
When you hover over the deprecated setup method, you have a hint.
You need to replace this:
await Purchases.setup(_apiKey);
to this:
PurchasesConfiguration(_apiKey);

GetStorage always returns null in flutter

Code
print("Before : ${GetStorage().read("XXX")}");
GetStorage().write("XXX", 1);
print("After : ${GetStorage().read("XXX")}");
This is my Code. Every time I run the App, the Output is
Before : null
After : 1
Why is the storage data getting cleared everytime I restart the App? I thought this was an alternative to SharedPreference which works just fine. Have I missed something?
Before anything, initialize the package, normally I do this on main.dart
main() async {
await GetStorage.init();
}
Create an instance from GetStorage, I always put a name on the box, if not it will put "GetStorage" by default. It needs to have a name so it can retrieve your data.
GetStorage getStorage = GetStorage('myData');
After that you can write and retrieve data from it, I recommend you to "await" all reads and writes.
await getStorage.write('XXX', 1);
var a = await getStorage.read('XXX');
print(a); /// 1
I recommend you to put a name on the box according to what you are storing.
You should await for GetStorage.init().
void main() async {
await GetStorage.init();
print("Before : ${GetStorage().read("XXX")}");
GetStorage().write("XXX", 1);
print("After : ${GetStorage().read("XXX")}");
}
final _userBox = () => GetStorage('User');
class UserPref {
void call(){
_userBox.call()..initStorage;
}
dynamic setValueInt(String key, int value) {
return 0.val(key, getBox: _userBox).val = value;
}
String setValue(String key, String value) {
return ''.val(key, getBox: _userBox).val = value;
}
dynamic getValueInt(String key) {
return (-1).val(key,getBox: _userBox).val;
}
dynamic getValue(String key) {
return ''.val(key,getBox: _userBox).val;
}
void setUser(User user) {
''.val('uname', getBox: _userBox).val = user.uname ?? '';
(-1).val('gender', getBox: _userBox).val = user.gender ?? -1;
''.val('born', getBox: _userBox).val = user.born.toString();
true.val('enabled', getBox: _userBox).val = user.enabled ?? true;
}
User getUser() {
final String? uname = ''.val('uname',getBox: _userBox).val;
final int? gender = (-1).val('gender',getBox: _userBox).val;
final DateTime? born = ''.val('born',getBox: _userBox).val == '' ? null : DateTime.parse(''.val('born',getBox: _userBox).val);
final bool? enabled = true.val('enabled',getBox: _userBox).val;
return User(
uname: uname,
gender: gender,
born: born,
enabled: enabled,
);
}
}
///INIT:
#override
void initState() {
//The init function must be written separately from the read/write function due to being asynchronous.
UserPref().call();
}
//OR
Future<void> main() async {
//await GetStorage.init();
UserPref().call();
}
///USAGE:
class MyStatefulWidget extends StatefulWidget {
final Users prefUser = UserPref().getUser();
...
}
//OR
#override
Widget build(BuildContext context) {
final Users prefUser = UserPref().getUser();
return ...;
}

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

When I pass pdf URL value to this its getting error with the built-in keyword "path" and it seems to be null?
loadPdf(String pdfPath) async {
setState(() => _isLoading = true);
var fileName = pdfPath.split('/').last;
var localFileUrl = (await Directory(CacheManager.getInstance().appDocumentDir.path +'/'+"realpro"+"/").create(recursive: true)).path +fileName;
if (await CacheManager.getInstance().checkFileExist(localFileUrl)) {
document = await PDFDocument.fromAsset(localFileUrl);
print(document);
setState(() {
_isLoading = false;
});
} else {
document = await PDFDocument.fromURL(pdfPath);
print(document);
setState(() {
_isLoading = false;
});
}
}
The getter 'path' was called on null.
The error means that the object for which you are writing object.path is null. You can use ?. operator like this: object?.something which is equivalent to:
object!=null ? object.something : null

Instance of 'Future<bool>, but expect bool

I am new in flutter.And i have a question.I have method checkIsExistByString to check if i have a data before to insert date in sqflite.I expect true or false.
class DbManager {
Future<bool> checkIsExistByString(String title) async {
await openDb();
var result = await _database
.rawQuery('SELECT $Title FROM $tableName WHERE $Title = ?', [title]);
return Future<bool>.value(result.isEmpty ? true : false);
}
}
When i try to use checkIsExistByString i expect bool, but i have Instance of 'Future
void _submit() async {
print(dbmanager.checkIsExistByString('Title'));//print -- Instance of 'Future<bool>',but i expect true
...
}
you need to put await.
print(await dbmanager.checkIsExistByString('Title'));
also there is no need to convert bool into Future<bool>.
return result.isEmpty ? true : false;
Use await keyword as below :
print(await dbmanager.checkIsExistByString('Title'));

Dart: How to return Future<void>

How can I return Future<void> ?
Future<void> deleteAll(List stuff){
stuff.forEach( s => delete(s)); //How do I return Future<void> when loop and all delete Operation are finished?
}
Future<void> delete(Stuff s) async {
....
file.writeAsString(jsonEncode(...));
}
How do I return Future<void> when the forEach loop and all delete Operations are finished?
You don't need to return anything manually, since an async function will only return when the function is actually done, but it depends on how/if you wait for invocations you do in this function.
Looking at your examples you are missing the async keyword, which means you need to write the following instead:
Future<void> deleteAll(List stuff) async {
stuff.forEach( s => delete(s));
}
Future<void> delete(Stuff s) async {
....
await file.writeAsString(jsonEncode(...));
}
When using Future<void> there is no need to explicitly return anything, since void is nothing, as the name implies.
Also make sure you call deleteAll and writeAsString() using await.
Note: To wait for all delete/foreach invocations to complete, see below answer for more details. In short you will need to put all delete invocations in a Future.wait for that.
You can't do that with forEach.
But you can use Future.wait and .map like this
Future<void> deleteAll(List stuff) {
return Future.wait(stuff.map((s) => delete(s)));
}
Future<void> delete(Stuff s) async{
....
await file.writeAsString(jsonEncode(...));
}
When to use async keyword:
You can use async when your function uses await keyword inside.
So when to use await keyword:
when you want to get the result from an asynchronous function and want do some logic on the result
Future<int> fetchCountAndValidate() asycn{
final result = await fetchCountFromServer();
if(result == null)
return 0;
else
return result;
}
When you want to call multiple asynchronous function
Future<int> fetchTotalCount() asycn{
final result1 = await fetchCount1FromServer();
final result2 = await fetchCount2FromServer();
return result1 + result2;
}
When you don't need async or await:
When you just calling another asynchronous function
Future<int> getCount(){
//some synchronous logic
final requestBody = {
"countFor": "..."
};
return fetchCountFromServer(requestBody); //this is an asynchronous function which returns `Future<int>`
}
For some rare cases we doesn't care about the completion of asynchronous function
void sendLogoutSignal(){
http.post(url, {"username" : "id0001"});
}

Categories

Resources