Instance of 'Future<bool>, but expect bool - android

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'));

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);

With or without async await I am getting this error on returning result

**With or without async await I am getting this error on returning result on line 26.
I am building a weather app but this is just a scratch file to test some things and concepts since I am learning from a Course called Flutter Beginner course. **
Error: The non-nullable local variable 'resolt' must be assigned before it can be used.
Code:
import 'dart:io';
void main() {
performTasks();
}
void performTasks() async {
task1();
String newtask2Result = await task2();
task3(newtask2Result);
}
void task1() {
String result = 'task 1 data';
print('Task 1 complete');
}
Future task2() async {
Duration threeSeconds = Duration(seconds: 3);
String resolt;
await Future.delayed(threeSeconds, () {
resolt = 'task 2 data';
print('Task 2 complete');
});
return resolt;
}
void task3(String task2Data) {
String result = 'task 3 data';
print('Task 3 complete with $task2Data');
}
Picture:
enter image description here
In then task2() function, you are declaring a variable but not initializing it.
You can either initialize it with default value or make it of type late.
Example 1 - default value
Future task2() async {
Duration threeSeconds = Duration(seconds: 3);
String resolt = "";
await Future.delayed(threeSeconds, () {
resolt = 'task 2 data';
print('Task 2 complete');
});
return resolt;
}
Example 2 - declaring as late
Future task2() async {
Duration threeSeconds = Duration(seconds: 3);
late String resolt;
await Future.delayed(threeSeconds, () {
resolt = 'task 2 data';
print('Task 2 complete');
});
return resolt;
}
Change your return type from Future to Future .

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

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

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;
});
});
}

Categories

Resources