Getting output as "Instance of 'Future<dynamic>'" in flutter - sqlite

I am trying get sum of a column in sqlite table using Bloc pattern.
debt_bloc.dart
getTotalAmount() async {
return await _debtRepository.getTotalAmt();
}
debt_dao.dart
Future<int> getTotalAmount() async {
final db = await dbProvider.database;
var result = await db.rawQuery("SELECT SUM(amount) FROM $debtDetailsTable");
int value = result[0]["SUM(amount)"];
return value;
}
debt_repositary.dart
Future getTotalAmount() => debtDao.getTotalAmount();
When i try to print like below
var total;
#override
void initState () {
super.initState();
_asyncMethod();
}
_asyncMethod() async {
var t = await debtBloc.getTotalAmount();
setState(() {
total = t;
});
}
print(total);
Output not updating when add new data. But if go back to home screen and come to respective screen value is updating.
Please guide me in right way. Thanks in advance

Await on your method first before printing it.
var total = await debtBloc.getTotalAmount(); // await here
print(total); // should now print some int value

Related

Can't assign a data value to a string - returns null - flutter

In my code, am trying a assign a string value to an empty string and display on the page but it keeps showing null but when I print it out, it shows the value.
String fName = '';
#override
void initState() {
super.initState();
getData();
}
getData() async {
FirebaseAuth _auth = FirebaseAuth.instance;
User _firebaseUser = _auth.currentUser;
print("============ MyHome ================");
print(_firebaseUser.uid);
_currentUser = await Database().getUserData(_firebaseUser.uid);
if (_currentUser != null) {
fName = _currentUser.firstName;
print(_currentUser.firstName);
}
}
database
Future<UserData> getUserData(String uid) async {
UserData returnValue = UserData();
try {
DocumentSnapshot _docSnapshot =
await _firestore.collection("users").doc(uid).get();
returnValue.uid = uid;
returnValue.firstName = _docSnapshot.data()["firstName"];
returnValue.lastName = _docSnapshot.data()["lastName"];
returnValue.userMail = _docSnapshot.data()["userMail"];
returnValue.userType = _docSnapshot.data()["userType"];
print("====================== on getData =============");
print(returnValue.firstName);
} catch (e) {
print(e);
}
return returnValue;
}
And whenever I try displaying the data it gives me null
Text("Hello, $fName"),
Please how do I do this or am I missing something
use setState to rebuild the widget tree with the value:
setState(() {
fName = _currentUser.firstName;
});
Since the getData function is async, flutter has already built the widget tree before getData finished. You'll now have to update the state using setstate.
setState(() {
fName = _currentUser.firstName;
});
You need to set the new state since we have made changes to the previous state (since your getData function is async.
setState(() {
fName = _currentUser.firstName;
});

Storing thumnail to SqlLite from Flutter App

Here i want to store the thumbnail to My database which is sqlite, and i am not able to store it. i am able to store it in local directory but. i wana call it from my data model. please help
Here is my Code.
_getThumb(videoPathUrl) async {
var appDocDir = await getApplicationDocumentsDirectory();
final folderPath = appDocDir.path;
print(folderPath);
String thumb = await Thumbnails.getThumbnail(
thumbnailFolder: folderPath,
videoFile: videoPathUrl,
imageType: ThumbFormat.JPEG,
quality: 25,
);
print('thumbnail: $thumb');
return thumb = model.thumbnail;
}
}
I Have Found a Solution "the Problem is not with the plugin or the method it adopts to store the Image" The problem is that it is not clear that how should a Unit8List is to be stored in the database.
In My case. __
I am Using this code to Store the Image.
_getThumb(videoPathUrl) async {
final thumb = await VideoThumbnail.thumbnailData(
video: videoPathUrl,
imageFormat: ImageFormat.JPEG,
maxWidth: 100,
maxHeight: 100,
quality: 75,
);
}
Then I am Using this final thumb to be saved against my VideoModel Variable of thumbnail
_getThumb(videoPathUrl) async {
final thumb = await VideoThumbnail.thumbnailData(
video: videoPathUrl,
imageFormat: ImageFormat.JPEG,
maxWidth: 100,
maxHeight: 100,
quality: 75,
);
print('thumbnail $thumb'); //Add these lines
model.thumbnail = thumb; //Add these Lines
return thumb; //Add these lines
}
And Once i have saved it i can see the print result in my debug console. Once i have that i am sure that it is saved.
Now i have to save it as a Blob in my db not as a String.
and thumbnail should be a Unit8List variable not a String Variable.
See the example
and in database
I am Also adding the full Video Model and DbHelper files for Others to use.
VideoModel.dart
import 'dart:typed_data';
import 'model.dart';
class VideoModel extends Model {
static String table = 'videos';
int id;
String videoName;
String video;
Uint8List thumbnail;
VideoModel({
this.id,
this.videoName,
this.video,
this.thumbnail,
});
static VideoModel fromMap(Map<String, dynamic> map) {
return VideoModel(
id: map["id"],
videoName: map['videoName'].toString(),
video: map['video'],
thumbnail: map['thumbnail'],
);
}
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
'id': id,
'videoName': videoName,
'video': video,
'thumbnail': thumbnail,
};
if (id != null) {
map['id'] = id;
}
return map;
}
}
DbHelper.dart
abstract class DB {
static Database _db;
static int get _version => 1;
static Future<void> init() async {
if (_db != null) {
return;
}
try {
var databasesPath = await getDatabasesPath();
String _path = p.join(databasesPath, 'video.db');
_db = await openDatabase(_path, version: _version, onCreate: onCreate);
} catch (ex) {
print(ex);
}
}
static void onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE videos (id INTEGER PRIMARY KEY AUTOINCREMENT, videoName STRING, video STRING, thumbnail BLOB)');
}
static Future<List<Map<String, dynamic>>> query(String table) async =>
_db.query(table);
static Future<int> insert(String table, Model model) async =>
await _db.insert(table, model.toMap());
static Future<int> update(String table, Model model) async => await _db
.update(table, model.toMap(), where: 'id = ?', whereArgs: [model.id]);
static Future<int> delete(String table, Model model) async =>
await _db.delete(table, where: 'id = ?', whereArgs: [model.id]);
static Future<Batch> batch() async => _db.batch();
}
Now when you have done these edits You can just all your image using
Image.memory(add your Image Here);
see example:
I hope that this will help some of you if you need help Let me know. Thanks

How can I wait for my future function in map function? (Flutter)

So, I'm building my app in Flutter and unfortunately, I have recently come across an error. So what I want to do in my TestProvider class is to get data from firestore (what getQuestionFromFirebase() function is doing), and after that happens, I want to create a map from DocumentSnapshot (what questionMapFromFirebase() function is doing). And there comes an error, because I can't async in map function so my function doesn't wait for the result from previous function, and returns null. Any solutions? *I tried to return map from getQuestionFromFirebase() - Future, but later I can't use value from it because, my function wants pure map.
class TestProvider {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<DocumentSnapshot> getQuestionFromFirebase(String documentId) async {
return await _firestore.collection('questions').doc(documentId).get();
}
Map questionMapFromFirebase(String documentId) {
Map questionMapFromFirebase;
getQuestionFromFirebase(documentId).then((DocumentSnapshot carSnapshot) => {
questionMapFromFirebase = carSnapshot.data(),
});
return questionMapFromFirebase;
}
}
Later I'm using this function there:
I'm using this function later there
List<Question> listOfQuestions() {
List<int> range = numberInRange(amountOfQuestions);
List<Question> listOfQuestions;
for (int i = 1; i <= amountOfQuestions; i++) {
listOfQuestions.add(Question.fromMap(
_testProvider.questionMapFromFirebase(range[1].toString())));
}
return listOfQuestions;
}
And that's creating error when Future occurs.
The argument type 'Future<Map<dynamic, dynamic>>' can't be assigned to the parameter type 'Map<String, dynamic>'.
Edit:
So recently I've made some changes to my code and now it looks like that
class TestProvider {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<DocumentSnapshot> getQuestionFromFirebase(String documentId) async {
return await _firestore.collection('questions').doc(documentId).get();
}
Future<Map> questionMapFromFirebase(String documentId) async {
DocumentSnapshot ds = await getQuestionFromFirebase(documentId);
return ds.data();
}
}
and repository
class TestRepository {
final int amountOfQuestions;
TestRepository({
#required this.amountOfQuestions,
});
TestProvider _testProvider;
Future listOfQuestions() async {
List<int> range = numberInRange(amountOfQuestions);
List<Question> listOfQuestions;
for (int i = 1; i <= amountOfQuestions; i++) {
listOfQuestions.add(Question.fromMap(
await _testProvider.questionMapFromFirebase(range[i].toString())));
}
return listOfQuestions;
}
}
The problem I started to see that is that every time i tried to call function questionMapFromFirebase from TestProvider, it has been working just fine. But when i tried to call it from TestRepository it throw the error:
E/flutter (13348): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method 'questionMapFromFirebase' was called on null.
E/flutter (13348): Receiver: null
E/flutter (13348): Tried calling: questionMapFromFirebase("2")
Any other sugestions how can I handle it?
Future<Map> questionMapFromFirebase(String documentId) async {
DocumentSnapshot ds = await getQuestionFromFirebase(documentId);
return ds.data();
}
Edit
check FutureBuilder class
example, it will be inside your widget tree where the list need to be shown.
return FutureBuilder(
future: _loadQuestions(),
builder: (context, snapshot) {
if(snapshot.connectionState == ConnectionState.done){
return widgetForListing(snapshot.data);
}
return Center(child: Text('Loading...'));
},
);
And your _loadQuestions function will be as
_loadQuestions() async {
List<int> range = numberInRange(amountOfQuestions);
List<Question> listOfQuestions = [];
for (int i = 1; i <= amountOfQuestions; i++) {
listOfQuestions.add(Question.fromMap(
await _testProvider.questionMapFromFirebase(range[1].toString())));
}
return listOfQuestions; //you can get this list in **snapshot.data** of future builder
}

Wait for stream inside a Future: Flutter

I want to check if the Firebase DB is connected or not, so I have to use a Future to return a boolean
Have a check at my code..
#override
Future<bool> isAvailable() async {
bool ret = false;
await firebaseInstance.reference().child('.info/connected').onValue.listen((event) {
ret = event.snapshot.value;
});
return ret;
}
the firebaseInstace.reference is a StreamSubscription type and does not wait for the future to return me a result.
please help.
If you only need to know the current value, use once().then instead of onValue.listen
#override
Future<bool> isAvailable() async {
var snapshot = await firebaseInstance.reference().child('.info/connected').once();
return snapshot.value;
}
Instead of awaiting the end of the stream subscription (it never ends), just take the first value:
#override
Future<bool> isAvailable() => firebaseInstance.reference().child('.info/connected').onValue.first;
You can put the StreamSubcription in a variable
StreamSubscription subscription = someDOMElement.onSubmit.listen((data) {
// you code here
if (someCondition == true) {
subscription.cancel();
}
});
More can be found here is there any way to cancel a dart Future?
You can do the following:
#override
Future<bool> isAvailable() async {
bool ret = false;
Stream<Event> events =
FirebaseDatabase.instance.reference().child('.info/connected').onValue;
await for (var value in events) {
ret = value.snapshot.value;
}
return ret;
}
onValue returns a Stream<Event> and then you can use await for to iterate inside the Stream and get the data, and then it will return.

Flutter Getting a specific Firestore document data and store it into a String variable

I am trying to get data from my Firestore and store the data into a String variable named time. Then put the variable into _event.
However, when I run the code, I got null, and I don't know why.
StateFulWidget...
String event;
Map<DateTime, List> _events;
#override
void initState() {
super.initState();
Firestore.instance.collection('events').document('2019-07-
30').get().then((
DocumentSnapshot ds) {
event = ds['time'];
});
_events = {
DateTime.parse("2019-08-01"): [event]
};
}
This is my Firestore document
I am new to Flutter and I have struggled for this question for a long time. Hope someone can help me
Thank you so much
UPDATE
I change my code.
However, I am still getting errors: The method [](Intance of 'DateTime') was called on null.
String event;
Map<DateTime, List> _events;
Future<String> getData()async{
final ds = await
Firestore.instance.collection('events').document('2019-07-30').get();
return ds['time'];
}
#override
void initState() {
super.initState();
getData().then((s) {
event = s;
//when I print(s), it showed the data correctly
});
_events = {
DateTime.parse("2019-08-01"): [event]
};
Can someone shows me where I got wrong?
Thank you!
You are not waiting for the result, ie _events = .. will run before .then() clause and that is why event variable is still null;
.get() is a Future so you need to await the result.
final ds = await Firestore.instance.collection('events').document('2019-07-
30').get();
event = ds['time'];
_events = {
DateTime.parse("2019-08-01"): [event]
};
This works for me :
Firestore().instance.collection('Collection Name')
.document('Document Name').get().then((data) async {
var dataReceive = data['property Name'];
}

Resources