Cannot query a document from a sub collection from Firestore collection - firebase

I am trying to query a specific document nested under collection'users/document'useruid'/collection'items'/'document'documentid'. I keep getting a 'null' value and it errors out:
try {
final user = await _auth.currentUser();
if (user != null) {
_loggedInUser = user;
_userUid = _loggedInUser.uid;
setState(() {
// showSpinner = false;
print(_userUid);
});
}
} catch (e) {
print(e);
}
}
void getItemDetail() async {
await _firestore
.collection('users')
.document(_userUid)
.collection('items')
.document(documentID)
.get()
.then((DocumentSnapshot snapshot) {
itemDetails = snapshot.data;
itemName = snapshot['item_name'];
itemNum = snapshot['item_num'.toString()];
itemDesc = snapshot['item_desc'];
itemLoc = snapshot['item_location'];
itemQty = snapshot['item_qty'.toString()];
itemUom = snapshot['item_uom'];
itemMfr = snapshot['item_mfr'];
itemStock = snapshot['out_of_stock'];
lastEditDate = snapshot['edit_date'];
createDate = snapshot['create_date'];
imageURL = snapshot['image_url'];
setState(() {
dateCreated =
new DateFormat.yMMMMd("en_US").format(createDate.toDate());
itemDetails = snapshot.data;
showSpinner = false;
stockCheck();
editDateCheck();
});
});
}
#override
void initState() {
testApp();
getCurrentUser();
getItemDetail();
// editDateCheck();
super.initState();
}
flutter error output:
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("item_name")
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 DocumentSnapshot.[] (package:cloud_firestore/src/document_snapshot.dart:29:42)
#2 _ItemDetailScreenState.getItemDetail.<anonymous closure> (package:simmanager/screens/item_detail_screen.dart:77:26)
#3 _rootRunUnary (dart:async/zone.dart:1132:38)
#4 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#5 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#6 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#7 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#8 Future._completeWithValue (dart:async/future_impl.dart:522:5)
#9 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
#10 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
#<…>
The documentid is passed from the navigator on previous page. I have printed (userid, documentid" all the values correctly print.

You should always check whether you're snapshot has any data or null like,
if(snapshot!=null)
Then you always should check the data inside snapshot is null or not like,
if(snapshot.data!=null)
Also, in your case you are calling you're data on null object.
I think you need to replace your snapshot['item_name'] with snapshot.data['item_name'] for all the item.
You are mistakenly calling snapshot["your_field"] instead of snapshot.data["your_field"] which is causing the issue.
Also, checking null safety while parsing the data from the network is recommended always.

Related

Flutter FirebaseFirestore: retrieving fields from an array of IDs

I'm trying to retrieve fields from multiple IDs that are stored in an array.
I have a collection of users, and in every user's document, there is an array of restaurant IDs of that user's owned restaurant as follows:
And each restaurant's document is one of those IDs in the array.
I successfully retrieved the array of ID's from the User but now I'm trying to get the names of the restaurant depending on the ID
I'm retrieving my ID's using this code:
var restaurantIDs = [];
getRestaurantIDs() async {
await FirebaseFirestore.instance
.collection("users")
.doc(user.uid)
.get()
.then((value) {
restaurantIDs = value.data()['rid'];
});
return restaurantIDs;
}
Then I'm trying to retrieve the names and save them in an array using this code:
var restaurantNames = [];
getRestaurantNames() async {
for (int i = 0; i < restaurantIDs.length; i++) {
await FirebaseFirestore.instance
.collection('restaurant')
.doc(restaurantIDs[i])
.get()
.then((value) {
restaurantNames = value.data()['name'];
});
}
return restaurantNames;
}
What am I doing wrong?
and thanks for the help.
EDIT:
1- I tried placing print statements inside the for loop, but it's like as if it's not going inside the loop at all, because the print statements don't get executed.
2- I think it's because the list of IDs won't be already stored inside the array when the function is called inside the initState, because I tried to print the length of the restaurantIDs array before the for loop and in initState and it showed 0, but when I print it inside the Scaffold, it would show 2.
EDIT 2:
I tried merging both functions into one to make sure that the restaurantIDs isn't empty, and now it goes inside the for loop because it prints out the statement, but now I receive another error
new function:
var restaurantIDs = [];
var restaurantNames = [];
getRestaurantIDs() async {
await FirebaseFirestore.instance
.collection("users")
.doc(user.uid)
.get()
.then((value) {
restaurantIDs = value.data()['rid'];
});
for (var i = 0; i < restaurantIDs.length; i++) {
print('added one');
await FirebaseFirestore.instance
.collection('restaurant')
.doc(restaurantIDs[i])
.get()
.then((value) {
restaurantNames.add(value.data()['name']);
});
}
return restaurantNames;
}
Error:
E/flutter (22920): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter (22920): Receiver: null
E/flutter (22920): Tried calling: []("name")
E/flutter (22920): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:68:5)
E/flutter (22920): #1 _AddMealScreenState.getRestaurantIDs.<anonymous closure>
package:bits_n_bobs/screens/add_meal_item_screen.dart:178
E/flutter (22920): #2 _rootRunUnary (dart:async/zone.dart:1436:47)
E/flutter (22920): #3 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter (22920): <asynchronous suspension>
E/flutter (22920): #4 _AddMealScreenState.getRestaurantIDs
E/flutter (22920): <asynchronous suspension>
E/flutter (22920):
There is something a bit off about the way you have organized your database. For each restaurant document, you should create a key with the user id as value, and then simply use the where query.
Example :
final restaurants = await FirebaseFirestore.instance.
.collection("restaurant")
.where("userId", isEqualTo: user.uid);
.get()
You can then map the retrieved list and filter the restaurant's name from it.
final restaurantNames = data.docs
.map((json) =>
json.data()["name"])
.toList();
Hope's that is hopefull.
restaurantNames.add( value.data()['name']);
Check the document id is matching.

Flutter compare num with dynamic from Firebase

I want to compare the App's version manually through Firebase Firestore. In Firestore, I have a collection(system) with a document(update) with a field: newest_v_app = number 7. I want to access this field on a page in my app and want to compare it to a number. If the number in firestore is higher than the number in the app, I want a bool to set to true.
The Code I tried (to explain what I mean):
UpdatePage.dart
class UpdatePage extends StatefulWidget {
#override
_UpdatePageState createState() => _UpdatePageState();
}
class _UpdatePageState extends State<UpdatePage> {
bool update_available = false;
num current_version = 7;
dynamic newest_version_from_firebase = 7;
Future<dynamic> _getUpdateAvailable() async {
final DocumentReference document = FirebaseFirestore.instance.collection('system').doc('update');
print('Success GetUpdate 1');
await document.get().then<dynamic>((DocumentSnapshot snapshot) async {
setState(() {
newest_version_from_firebase = snapshot.data;
});
});
print('Success GetUpdate 2');
compareUpdate(context);
print('Success GetUpdate 3');
testUpdateComparer();
}
void compareUpdate(BuildContext context) {
if (newest_version_from_firebase > current_version) {
setState(() {
update_available = true;
});
} else {
setState(() {
update_available = false;
});
}
}
void testUpdateComparer() {
if (update_available == true) {
print('Success AvailableBool');
} else {
print('No AvailableBool');
}
}
#override
void initState() {
super.initState();
print('Success Init');
_getUpdateAvailable();
}
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
return Scaffold(
);
}
}
Console & Error:
I/flutter (15814): Success Init
I/flutter (15814): Success GetUpdate 1
W/DynamiteModule(15814): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(15814): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(15814): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
I/flutter (15814): Success GetUpdate 2
I/flutter (15814): No AvailableBool
E/flutter (15814): [ERROR:flutter/lib/ui/ui_dart_state.cc(213)] Unhandled Exception: NoSuchMethodError: Closure call with mismatched arguments: function '>'
E/flutter (15814): Receiver: Closure: () => Map<String, dynamic>? from Function 'data':.
E/flutter (15814): Tried calling: >(7)
E/flutter (15814): Found: >() => Map<String, dynamic>?
E/flutter (15814): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:63:5)
E/flutter (15814): #1 _UpdatePageState.compareUpdate (package:myapp/UpdatePage/UpdatePage.dart:44:38)
E/flutter (15814): #2 _UpdatePageState._getUpdateAvailable (package:myapp/UpdatePage/UpdatePage.dart:38:5)
E/flutter (15814): <asynchronous suspension>
E/flutter (15814):
Flutter 2.3.0-17.0.pre.19 • channel master • https://github.com/flutter/flutter.git
Framework • revision bcf05f4587 (4 months ago) • 2021-05-23 02:19:02 -0400
Engine • revision 8cd4cf0a67
Tools • Dart 2.14.0 (build 2.14.0-143.0.dev)
The snapshot.data returns a Map<String, dynamic> from firestore and you're trying to assign it to the variable newest_version_from_firebase that you're trying to use as a number, which is not possible.
snaposhot.data returns a Document in which your have your version number probably stored as a key value pair, like: {"versionNumber": 7}
to access it your should do, for example:
newest_version_from_firebase = snapshot.data["versionNumber"] as int;
Solved it:
Changed num to int
late DocumentSnapshot snapshot;
int current_version = 7;
int newest_version_from_firebase = 7;
void getUpdateAvailable() async {
final data = await FirebaseFirestore.instance.collection("system").doc("update").get() as DocumentSnapshot;
snapshot = data as DocumentSnapshot;
setState(() {
newest_version_from_firebase = snapshot["newest_version"] as int;
});
print(newest_version_from_firebase.toString());
compareUpdate(context);
}

The function I wrote to fetch data in the database returns empty. There is data in the database. In flutter

======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Notlar(dirty, state: _NotlarState#20db1):
The method 'notListesiniGetir' was called on null.
Receiver: null
Tried calling: notListesiniGetir()
Photo-3 code here:
[Future<int> kategoriSil(int kategoriID) async {
var db= await _getDatabase();
var sonuc= await db.delete("kategori", where: 'kategoriID= ?', whereArgs: \[kategoriID\]);
return sonuc;
}
Future<List<Map<String, dynamic>>> notlariGetir() async {
var db = await _getDatabase();
var sonuc= await db.rawQuery('select * from "not" inner join kategori on kategori.kategorID = "not".kategoriID;');
return sonuc;
}
Future<List<Not>> notListesiniGetir() async{
var notlarMapListesi = await notlariGetir();
var notListesi = List<Not>();
for(Map map in notlarMapListesi){
notListesi.add(Not.fromMap(map));
}
return notListesi;
}][1]
error code:======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Notlar(dirty, state: _NotlarState#20db1):
The method 'notListesiniGetir' was called on null.
Receiver: null
Tried calling: notListesiniGetir()
The relevant error-causing widget was:
Notlar file:///C:/Flutter%20calismalari/not_sepeti/lib/main.dart:63:27
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 _NotlarState.build (package:not_sepeti/main.dart:166:30)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4802:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4685:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4857:11)
...
enter image description hereBwg.png
The problem is not in your code but in your screenshot (that you should add to your question as a code snippet).
You have to await the condition snapshot.hasData
Change from
If (snapshot.connectionState == ConnectionState.done)
To
If (snapshot.connectionState == ConnectionState.done && snapshot.hasData)
Also
var notListesi = List<Not>()
List<Not> notListesi = <Not>[ ]; // better
And more importantly remove DatabaseHelper in your init state:
DatabaseHelper databaseHelper = DatabaSeHelper();
To
databaseHelper = DatabaseHelper();
it will be working.

Error database_closed when using flutter's sqflite

I try to use sqflite to save some data like my class Movie but when i try to insert or query on the database, see this message:
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: DatabaseException(error database_closed)
my MovieBloc class:
List<Movie> _movies = new List<Movie> ();
class MoviesBloc implements BaseBloc {
final _moviesController = StreamController<List<Movie>>();
Database moviesDB;
String _moviesPath;
Stream<List<Movie>> get moviesStream => _moviesController.stream;
List<Movie> get movies => _movies;
int getLengthMovieList() {
return _movies.length;
}
clearMovieList() {
_movies.clear();
}
Future<void> openMovieDB({String dbName:'movies.db'}) async {
var databasesPath = await getDatabasesPath();
_moviesPath = join(databasesPath, dbName);
moviesDB = await openDatabase(_moviesPath, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
'CREATE TABLE movies (Id INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT NOT NULL, imdbRating TEXT, Poster TEXT, Plot TEXT, Saved INTEGER DEFAULT 0)');
});
}
Future<void> closeMovieDB() async => moviesDB.close();
void dispose() {
_moviesController.close();
}
}
my MovieProvider class:
class MovieProvider extends MoviesBloc {
String _tableName = 'movies';
Future<Movie> insert(Movie movie, {conflictAlgorithm: ConflictAlgorithm.ignore}) async {
await moviesDB.insert(_tableName, movie.toMap(), conflictAlgorithm: conflictAlgorithm);
return movie;
}
Future<bool> insertAll(List<Movie> movies) async {
await Future.wait(movies.map((movie) async {
await this.insert(movie);
}
));
return true;
}
Future<List<Movie>> paginate(int page, {int limit: 15}) async {
print('in Paginate to SQLite');
List<Map> maps = await moviesDB.query(_tableName,
columns: ['Id', 'Title', 'imdbRating', 'Poster', 'Plot', 'Saved'],
limit: limit,
offset: page == 1 ? 0 : ((page -1) * limit)
);
List<Movie> movies = new List<Movie> ();
if (maps.length > 0) {
maps.map((movie) {
movies.add(Movie.fromJson(movie));
}
);
}
return movies;
}
}
my save method to sqflite:
static Future<bool> saveAllMoviesIntoSqlite(List<Movie> movies) async {
var db = new MovieProvider();
await db.openMovieDB();
await db.insertAll(movies);
await db.closeMovieDB();
return true;
}
my load method from sqflite:
static Future<Map> getAllMoviesFromSqlite(int page) async {
var db = new MovieProvider();
await db.openMovieDB();
List<Movie> movies = new List<Movie> ();
movies = await db.paginate(page);
await db.closeMovieDB();
return {
"currentPage": page,
"movies": movies
};
}
I observe that in insertAll method from MovieProvider class for insert any movie from the movies list to sq with await and async:
Future<bool> insertAll(List<Movie> movies) async {
await Future.wait(movies.map((movie) async {
await this.insert(movie);
}
));
return true;
}
I try to close and open database sometimes sequential and other plays with close and open database ...
my log:
I/flutter ( 1617): in Paginate to SQLite
E/flutter ( 1617): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: DatabaseException(error database_closed)
E/flutter ( 1617): #0 SqfliteDatabaseMixin.checkNotClosed (package:sqflite_common/src/database_mixin.dart:282:7)
E/flutter ( 1617): #1 SqfliteDatabaseExecutorMixin._rawQuery (package:sqflite_common/src/database_mixin.dart:125:8)
E/flutter ( 1617): #2 SqfliteDatabaseExecutorMixin.query (package:sqflite_common/src/database_mixin.dart:110:12)
E/flutter ( 1617): #3 MovieProvider.paginate (package:umdb/bloc/movie_provider.dart:24:38)
E/flutter ( 1617): #4 MovieService.getAllMoviesFromSqlite (package:umdb/services/movie_service.dart:54:23)
E/flutter ( 1617): <asynchronous suspension>
E/flutter ( 1617): #5 MovieService.getSavedFromSQ (package:umdb/services/movie_service.dart:95:26)
E/flutter ( 1617): #6 MovieService.fetchSavedMovies (package:umdb/services/movie_service.dart:105:5)
E/flutter ( 1617): <asynchronous suspension>
E/flutter ( 1617): #7 MovieDetailState.build.<anonymous closure>.<anonymous closure> (package:umdb/ui_widgets/movie_detail.dart:168:42)
E/flutter ( 1617): #8 State.setState (package:flutter/src/widgets/framework.dart:1240:30)
E/flutter ( 1617): #9 MovieDetailState.build.<anonymous closure> (package:umdb/ui_widgets/movie_detail.dart:142:27)
E/flutter ( 1617): #10 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter ( 1617): #11 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter ( 1617): #12 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter ( 1617): #13 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:256:7)
E/flutter ( 1617): #14 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:158:27)
E/flutter ( 1617): #15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:224:20)
E/flutter ( 1617): #16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter ( 1617): #17 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter ( 1617): #18 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter ( 1617): #19 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter ( 1617): #20 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 1617): #21 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 1617): #22 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 1617): #23 _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter ( 1617): #24 _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
please help me to fix it
It is very hard to deal with opening/closing the database. There are indeed many cases where you might access a closed database and even worse, if you open twice the same database, you get the same instance so the first close will close the database.
Personally I recommend keeping the database open.
If you need to handle multiple databases and open/close them for short actions, make sure you have the proper mutex/lock mechanism so that you control how your database is opened/accessed/closed without any other method trying to access the same database at the same time (ok that part is not clear sorry).
Something like that (although I really don't recommend opening/closing each time):
import 'package:synchronized/synchronized.dart';
final static _lock = Lock();
static Future<bool> saveAllMoviesIntoSqlite(List<Movie> movies) async {
return _lock.synchronized(() {
var db = new MovieProvider();
await db.openMovieDB();
await db.insertAll(movies);
await db.closeMovieDB();
return true;
});
}
static Future<Map> getAllMoviesFromSqlite(int page) async {
return _lock.synchronized(() {
var db = new MovieProvider();
await db.openMovieDB();
List<Movie> movies = new List<Movie> ();
movies = await db.paginate(page);
await db.closeMovieDB();
return {
"currentPage": page,
"movies": movies
};
});
}
You need to set null for your database instance when you close your database. Otherwise it will always return the old instance.
Future close() async {
final db = await instance.database;
_database = null;
return db.close();
}
Keeping database without close, and using Singleton pattern is a good choice to solve this problem.
1- Create new file sql_lite_service.dart, this will contains SqlLiteService class with this full code:
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class SqlLiteService {
String dBName = 'my_db_name';
int dBVersion = 1;
// Singleton pattern
static final SqlLiteService _databaseService = SqlLiteService._internal();
factory SqlLiteService() => _databaseService;
SqlLiteService._internal();
static Database? _database;
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
Future<Database> _initDatabase() async {
// Set the version. This executes the onCreate function and provides a
// path to perform database upgrades and downgrades.
Database db = await _getDB();
return db;
}
Future<Database> _getDB() async{
final path = await _getPath(); // Get a location using getDatabasesPath
return await openDatabase(
path,
onCreate: _onCreate,
version: dBVersion,
onConfigure: (db) async => await db.execute('PRAGMA foreign_keys = ON'),
);
}
// create tables
Future<void> _onCreate(Database db, int version) async {
// Run the CREATE {users} TABLE statement on the database.
await db.execute(
'CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, created_at datetime default current_timestamp, updated_at datetime default current_timestamp)'
);
// todo: Add your code here ...
}
Future<String> _getPath() async {
String databasesPath = await getDatabasesPath();
String path = join(databasesPath, dBName);
return path;
}
}
2- Now you can get Database instance from any other class by:
final Database database = await SqlLiteService().database;
// usage example
await database.rawDelete(
'DELETE FROM users WHERE id = ?',
[1]
);
Using this way will solve database_closed error...

Trouble with Dart Futures in Flutter : Failed assertion: line 146: '<optimized out>': is not true

I'm building a user authentication module for my app and I am running into trouble with some asynchronous code.
Firstly, here is the error that is thrown:
E/flutter (17162): [ERROR:flutter/shell/common/shell.cc(188)] Dart Error: Unhandled exception:
E/flutter (17162): 'dart:async/future_impl.dart': Failed assertion: line 146: 'optimized out': is not true.
E/flutter (17162): #0 _AssertionError._doThrowNew (dart:core/runtime/liberrors_patch.dart:40:39)
E/flutter (17162): #1 _AssertionError._throwNew (dart:core/runtime/liberrors_patch.dart:36:5)
E/flutter (17162): #2 _FutureListener.handleError (dart:async/future_impl.dart:146:14)
E/flutter (17162): #3 Future._propagateToListeners.handleError (dart:async/future_impl.dart:654:47)
E/flutter (17162): #4 Future._propagateToListeners (dart:async/future_impl.dart:675:24)
E/flutter (17162): #5 Future._completeError (dart:async/future_impl.dart:494:5)
E/flutter (17162): #6 _SyncCompleter._completeError (dart:async/future_impl.dart:55:12)
E/flutter (17162): #7 _Completer.completeError (dart:async/future_impl.dart:27:5)
E/flutter (17162): #8 _AsyncAwaitCompleter.completeError (dart:async/runtime/libasync_patch.dart:40:18)
E/flutter (17162): #9 FirebaseAuth.signInWithEmailAndPassword (package:firebase_auth/firebase_auth.dart)
E/flutter (17162):
E/flutter (17162): #10 Session.login. (package:mood_map/utilities/session.dart:31:24)
E/flutter (17162): #11 _RootZone.runUnary (dart:async/zone.dart:1379:54)
E/flutter (17162): #12 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
E/flutter (17162): #13 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:642:45)
E/flutter (17162): #14 Future._propagateToListeners (dart:async/future_impl.dart:671:32)
E/flutter (17162): #15 Future._complete (dart:async/future_impl.dart:476:7)
E/flutter (17162): #16 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
E/flutter (17162): #17 _AsyncAwaitCompleter.complete (dart:async/runtime/libasync_patch.dart:28:18)
E/flutter (17162): #18 _completeOnAsyncReturn (dart:async/runtime/libasync_patch.dart:295:13)
E/flutter (17162): #19 Session._checkUserAlreadyExists (package:mood_map/utilities/session.dart)
E/flutter (17162):
E/flutter (17162): #20 Session.login (package:mood_map/utilities/session.dart:27:11)
And here are the functions that are involved:
static final FirebaseAuth _authenticator = FirebaseAuth.instance;
static void login(BuildContext context, String email, String password) async {
email = email.trim();
password = password.trim();
//Check if the user already exists
await _checkUserAlreadyExists(email).then((exists) {
if(exists) {
_authenticator.signInWithEmailAndPassword(email: email, password: password)
.then((FirebaseUser user) { _loginSuccess(); })
.catchError((Error e) { _loginFailure(context); });
} else {
Utilities.showMessageDialog(context, "That user doesn't exist. Please create an account below.");
}
});
}
----------------------------------------------------------------------
static Future createUserAccount(BuildContext context, email, String password) async {
//Check if the user already exists
await _checkUserAlreadyExists(email).then((exists) {
if(exists) {
Utilities.showMessageDialog(context, "That user already exists. Please login or select another account.");
AppNavigator.navigateToLoginScreen();
} else {
_authenticator.createUserWithEmailAndPassword(email: email, password: password)
.then((FirebaseUser user) { _createUserSuccess(); })
.catchError((Error e) { _createUserFailure(context); });
}
});
}
In short, the call to _authenticator.signonWithEmailAndPassword() is failing. I know that the _authenticator instance is working with other functions so I know it isnt a problem with Firebase itself.
I am worried that I am doing something incorrectly by calling another asynchronous function, _authenticator.signonWithEmailAndPassword() from within another asynchronous function, _checkIfUserAlreadyExists(). It seems that this should be okay to do from within a .then() block from what I've read but the error message seems pretty insistent that it is something to do with the setup of the asynchronous nature of the function calls.
Thoughts?
If you use .then() clauses don't use await.
.then() and await are two different ways to handle Future's but shouldn't be used for the same Future instance.
Consider using async - await to catch the errors in the 'final step'. This answer https://github.com/flutter/flutter/issues/22734 helped me a lot.
Below is a code snippet I got from a source I can't remember but it helped me understand how to properly work with Futures. I modified it a little bit to test for my exact situation (added main4() and divideFullAsyncNested() functions). I hope it helps.
// SO 29378453
import 'dart:async';
import 'package:login_app/constants.dart';
main() {
// fails
main1();
main2();
main3();
main4();
}
Future<double> divide(int a, b) {
// this part is still sync
if (b == 0) {
throw new Exception('Division by zero divide non-async');
}
// here starts the async part
return new Future.value(a / b);
}
Future<double> divideFullAsync(int a, b) {
return new Future(() {
if (b == 0) {
throw new Exception('Division by zero full async');
}
return new Future.value(a / b);
// or just
// return a / b;
});
}
Future<double> divideFullAsyncNested() {
return divideFullAsync(7, 8).then(
(val) {
return divideFullAsync(5, 0).then(
(val2) {
return Future(() {
if (val2 == 1) {
throw Exception('Innermost: Result not accepted exception.');
}
return val2;
});
},
).catchError((err) => throw Exception('Inner: $err'));
},
).catchError((err) => throw Exception('Outter: $err'));
}
//Future<double> divideFullAsyncNested() {
// return divideFullAsync(9, 9).then(
// (val) {
// return Future(
// () {
// if (val == 1) {
// throw Exception('Result not accepted exception.');
// }
// return val;
// },
// );
// },
// ).catchError((err) => throw Exception(err.toString()));
//}
// async error handling doesn't catch sync exceptions
void main1() async {
try {
// divide(1, 0).then((result) => print('(1) 1 / 0 = $result')).catchError(
// (error) => print('(1)Error occured during division: $error'));
var result = await divide(1, 0);
print('(1) 1 / 0 = $result');
} catch (ex) {
print('(1.1)Error occured during division: ${ex.toString()}');
}
}
// async error handling catches async exceptions
void main2() {
divideFullAsync(1, 0)
.then((result) => print('(2) 1 / 0 = $result'))
.catchError(
(error) => print('(2) Error occured during division: $error'));
}
// async/await allows to use try/catch for async exceptions
main3() async {
try {
await divideFullAsync(1, 0);
print('3');
} catch (error) {
print('(3) Error occured during division: $error');
}
}
main4() async {
// try {
// await divideFullAsyncNested();
// } on Exception catch (e) {
// print("(4) ${e.toString().replaceAll('Exception:', '').trimLeft().trimRight()}");
// }
try {
divideFullAsyncNested()
.then((v) => print(v))
.catchError((err) => print(Constants.refinedExceptionMessage(err)));
} on Exception catch (e) {
print("(4) ${Constants.refinedExceptionMessage(e)}");
}
}

Resources