Unhandled Exception: NoSuchMethodError: The method '[]' was called on null - firebase

I have a problem with showing dialog.
When i'm sending push notofication to the device i have error. But the audio play, -->
assetsAudioPlayer.open(
Audio('sounds/alert.mp3'),
);
assetsAudioPlayer.play();
and first dialog --->
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) => ProgressDialog(status: 'received trip..',),
);
i also can see.
void fetchRideInfo(String rideID, context){
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) => ProgressDialog(status: '..',),
);
DatabaseReference rideRef = FirebaseDatabase.instance.reference().child('rideRequest/$rideID');
rideRef.once().then((DataSnapshot snapshot) {
Navigator.pop(context);
if(snapshot.value != null){
assetsAudioPlayer.open(
Audio('sounds/alert.mp3'),
);
assetsAudioPlayer.play();
double pickupLat = double.parse(snapshot.value["location"]["latitude"].toString()); //**error HERE**
double pickupLng = double.parse((snapshot.value["location"]["longitude"].toString()));
String pickupAddress = snapshot.value['pickup_address'].toString();
double destinationLat = double.parse(snapshot.value['destination']['latitude'].toString());
double destinationLng = double.parse(snapshot.value['destination']['longitude'].toString());
String destinationAddress = snapshot.value['destination_address'];
String paymentMethod = snapshot.value['payment_method'];
TripDetails tripDetails = TripDetails();
tripDetails.rideID = rideID;
tripDetails.pickupAddress = pickupAddress;
tripDetails.destinationAddress = destinationAddress;
tripDetails.pickup = LatLng(pickupLat , pickupLng);
tripDetails.destination = LatLng(destinationLat, destinationLng);
tripDetails.paymentMethod = paymentMethod;
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) => NotificationDialog(tripDetails: tripDetails,),
);
}
});
}
THIS MY CONSOLE
E/FlutterFcmService(11685): Fatal: failed to find callback
I/flutter (11685): ride_id: -MPRCo9pHbzEi1pOJOAs
E/flutter (11685): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter (11685): Receiver: null
E/flutter (11685): Tried calling: []("latitude")
E/flutter (11685): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (11685): #1 PushNotificationService.fetchRideInfo.<anonymous closure> (package:cab_driver/helpers/pushnotificationservice.dart:82:68)
E/flutter (11685): #2 _rootRunUnary (dart:async/zone.dart:1194:47)
E/flutter (11685): #3 _CustomZone.runUnary (dart:async/zone.dart:1097:19)
E/flutter (11685): #4 _FutureListener.handleValue (dart:async/future_impl.dart:150:18)
E/flutter (11685): #5 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:703:45)
E/flutter (11685): #6 Future._propagateToListeners (dart:async/future_impl.dart:732:32)
E/flutter (11685): #7 Future._completeWithValue (dart:async/future_impl.dart:536:5)
E/flutter (11685): #8 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:254:13)
E/flutter (11685): #9 Query.once (package:firebase_database/src/query.dart)
E/flutter (11685): <asynchronous suspension>
E/flutter (11685):
I dont find any information about this. Many solution about NoSuchMethodError, but HOW implement to my PROBLEM? I dont know. Please help.

Related

How to go from one page to another depending on the data they receive when opening the app

I am trying to make an application that has three types of users: Students, Teachers and Parents, what I do is save the id of the user token using shared_preferences at login, and I want it to search the database when entering the app and depending on what type of user it is, go to its corresponding page
So far i'm trying this
import 'package:app_plantel/padres_page.dart';
import 'package:app_plantel/profesores_page.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
isLogged(context);
return new Scaffold(
body: Center(
child: Icon(
Icons.beach_access,
),
),
);
}
}
Future<String> _returnValue() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final token = await prefs.getString("token");
return token;
}
Future isLogged(context) async {
await FirebaseFirestore.instance
.collection('Padres')
.doc(_returnValue().toString())
.get()
.then((DocumentSnapshot documentSnapshot) async {
if (documentSnapshot.exists) {
Navigator.of(context).push(MaterialPageRoute(builder: (context)=> PadresPage()));
} else {
await FirebaseFirestore.instance
.collection('Alumnos')
.doc(_returnValue().toString())
.get()
.then((DocumentSnapshot documentSnapshot) async {
if (documentSnapshot.exists) {
Navigator.of(context).push(MaterialPageRoute(builder: (context)=> AlumnosPage()));
} else {
await FirebaseFirestore.instance
.collection('Profesores')
.doc(_returnValue().toString())
.get()
.then((DocumentSnapshot documentSnapshot) async {
if (documentSnapshot.exists) {
Navigator.of(context).push(MaterialPageRoute(builder: (context)=> ProfesoresPage()));
} else {
Navigator.of(context).push(MaterialPageRoute(builder: (context)=> LoginPage()));
}
});
}
});
}
});
}
But it throws me a lot of mistakes:
E/flutter (13461): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
E/flutter (13461): The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
E/flutter (13461): #0 Navigator.of.<anonymous closure> (package:flutter/src/widgets/navigator.dart:2553:9)
E/flutter (13461): #1 Navigator.of (package:flutter/src/widgets/navigator.dart:2560:6)
E/flutter (13461): #2 isLogged.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:app_plantel/main.dart:53:27)
E/flutter (13461): #3 isLogged.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:app_plantel/main.dart:49:19)
E/flutter (13461): #4 _rootRunUnary (dart:async/zone.dart:1436:47)
E/flutter (13461): #5 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter (13461): <asynchronous suspension>
E/flutter (13461): #6 isLogged.<anonymous closure>.<anonymous closure> (package:app_plantel/main.dart:45:13)
E/flutter (13461): <asynchronous suspension>
E/flutter (13461): #7 isLogged.<anonymous closure> (package:app_plantel/main.dart:37:9)
E/flutter (13461): <asynchronous suspension>
E/flutter (13461): #8 isLogged (package:app_plantel/main.dart:29:3)
E/flutter (13461): <asynchronous suspension>
E/flutter (13461):
I would like to know how to solve it or some other method that they propose to be able to do it
The exception is thrown because you don't have a MaterialApp or a CupertinoApp widget above your Scaffold, and it is needed for navigation. Something like this:
return const MaterialApp(
home: Scaffold(
body: Center(
child: Icon(
Icons.beach_access,
),
),
)
);
Besides, your isLogged function is async, but you can't await it in the build method. Consider using a FutureBuilder to wait for the database responses before you start building the main widget.
The context you passed in isLogged method is not wrapped with navigator.
You can set a global variable final _navKey = GlobalKey<NavigatorState>();
then wrap you UI with Material app and set material app navigator key
const MaterialApp(
home: Scaffold(
body: Center(
child: Icon(
Icons.beach_access,
),
),
),
navigatorKey: _navKey
);
Finally use the key to retrieve navigator context and use when calling your navigator _navKey.currentState?.context

While uploading user avatar image to firebase while registering with email gives null value when using getter to get ImageUrl

So I am trying to upload user avatar to firebase storage while registering to firebase auth with email and password and simultaneously adding it to cloud firestore , but the image I upload using imageFilePicker returns null when trying to get it.
I am using provider for state management. I am new to this.
Image Upload code :
class FirebaseOperations with ChangeNotifier {
UploadTask imageUploadTask;
String initUserEmail, initUserName, initUserImage;
String get getInitUserName => initUserName;
String get getInitUserEmail => initUserEmail;
String get getInitUserImage => initUserImage;
Future uploadUserAvatar(BuildContext context) async {
Reference imageReference = FirebaseStorage.instance
.ref()
.child('userProfileAvatar/${DateTime.now()}');
imageUploadTask = imageReference.putFile(
Provider.of<ImageSelect>(context, listen: false).getUserAvatar);
await imageUploadTask.whenComplete(() {
print('Image uploaded!');
});
imageReference.getDownloadURL().then((url) {
print("################################################" + url);
Provider.of<ImageSelect>(context, listen: false).userAvatarUrl =
url.toString();
print(
'the user profile avatar url => ${Provider.of<ImageSelect>(context, listen: false).userAvatarUrl}');
notifyListeners();
});
}
Future initUserData(BuildContext context) async {
return FirebaseFirestore.instance
.collection('users')
.doc(Provider.of<Authentication>(context, listen: false).getUserUid)
.get()
.then((doc) {
print('Fetching user data');
initUserName = doc.data()['username'];
initUserEmail = doc.data()['useremail'];
initUserImage = doc.data()['userimage'];
print(initUserName);
print(initUserEmail);
print(initUserImage);
notifyListeners();
});
}
}
Image select code :
class ImageSelect with ChangeNotifier {
final picker = ImagePicker();
File userAvatar;
File get getUserAvatar => userAvatar;
String userAvatarUrl;
String get getUserAvatarUrl => userAvatarUrl;
Future pickUserAvatar(BuildContext context, ImageSource source) async {
final pickedUserAvatar = await picker.getImage(source: source);
pickedUserAvatar == null
? print('Select image')
: userAvatar = File(pickedUserAvatar.path);
// print(userAvatar.path);
if (userAvatar != null) {
await Provider.of<FirebaseOperations>(context, listen: false)
.uploadUserAvatar(context);
} else
print('Image not Selected ');
notifyListeners();
}
Register Button code :
GestureDetector(
onTap: () {
if (_emailController.text.isNotEmpty) {
Provider.of<Authentication>(context, listen: false)
.createAccount(
_emailController.text, _passwordController.text)
.whenComplete(() {
print('Creating collection...');
Provider.of<FirebaseOperations>(context, listen: false)
.createUserCollection(context, {
'userpassword': _passwordController.text,
'useruid':
Provider.of<Authentication>(context, listen: false)
.getUserUid,
'useremail': _emailController.text,
'username': _fullNameController.text,
'usermobile': _phoneNumberController.text,
'userimage':
Provider.of<ImageSelect>(context, listen: true)
.getUserAvatarUrl,
});
}).whenComplete(() {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => HomeScreen()));
});
} else {
warningText(context, 'Fill all the data!');
}
},
Error Code:
I/flutter (30433): Image uploaded!
I/flutter (30433):
################################################https://firebasestorage.googleapis.com/v0/b/bubblez-
e2801.appspot.com/o/userProfileAvatar%2F2021-03-25%2011%3A34%3A39.688986?alt=media&token=78a2be55-
b45c-453e-a398-02a363178d9d
E/flutter (30433): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Looking up a
deactivated widget's ancestor is unsafe.
E/flutter (30433): At this point the state of the widget's element tree is no longer stable.
E/flutter (30433): To safely refer to a widget's ancestor in its dispose() method, save a reference
to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's
didChangeDependencies() method.
E/flutter (30433): #0 Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure>
package:flutter/…/widgets/framework.dart:3864
E/flutter (30433): #1 Element._debugCheckStateIsActiveForAncestorLookup
package:flutter/…/widgets/framework.dart:3878
E/flutter (30433): #2 Element.getElementForInheritedWidgetOfExactType
package:flutter/…/widgets/framework.dart:3905
E/flutter (30433): #3 Provider._inheritedElementOf
package:provider/src/provider.dart:327
E/flutter (30433): #4 Provider.of
package:provider/src/provider.dart:284
E/flutter (30433): #5 FirebaseOperations.uploadUserAvatar.<anonymous closure>
package:bubblez/…/authMethods/FirebaseOperations.dart:27
E/flutter (30433): #6 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (30433): #7 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (30433): #8 _FutureListener.handleValue (dart:async/future_impl.dart:152:18)
E/flutter (30433): #9 Future._propagateToListeners.handleValueCallback
(dart:async/future_impl.dart:704:45)
E/flutter (30433): #10 Future._propagateToListeners (dart:async/future_impl.dart:733:32)
E/flutter (30433): #11 Future._completeWithValue (dart:async/future_impl.dart:539:5)
E/flutter (30433): #12 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:254:13)
E/flutter (30433): #13 MethodChannelReference.getDownloadURL
(package:firebase_storage_platform_interface/src/method_channel/method_channel_reference.dart)
package:firebase_storage_platform_interface/…/method_channel/method_channel_reference.dart:1
E/flutter (30433): <asynchronous suspension>
E/flutter (30433):
I/flutter (30433): Fetching user data
E/flutter (30433): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception:
NoSuchMethodError: The method '[]' was called on null.
E/flutter (30433): Receiver: null
E/flutter (30433): Tried calling: []("username")
E/flutter (30433): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (30433): #1 FirebaseOperations.initUserData.<anonymous closure>
package:bubblez/…/authMethods/FirebaseOperations.dart:50
E/flutter (30433): #2 _rootRunUnary (dart:async/zone.dart:1362:47)
Your problem is in this function
Future initUserData(BuildContext context) async {
return FirebaseFirestore.instance
.collection('users')
.doc(Provider.of<Authentication>(context, listen: false).getUserUid)
.get()
.then((doc) {
print('Fetching user data')});}
Because in your debug console, I read the line saying Image uploaded!, can you confirm that an Image URL and username have been posted to firestore?
Try changing it to this:
Future initUserData(BuildContext context) async {
return await FirebaseFirestore.instance //<=== adding await here
.collection('users')
.doc(Provider.of<Authentication>(context, listen: false).getUserUid)
.get()
.then((doc) {
initUserName = doc.data()['username'];
initUserEmail = doc.data()['useremail'];
initUserImage = doc.data()['userimage'];
print(initUserName);
print(initUserEmail);
print(initUserImage);
notifyListeners();
});
}
And update on what happens. Because your error log also says that ['username'] was called on null, which is only the first one of your inquires, it's not reaching the point to image or email.
If this doesn't work, we can try working with the BuildContext that is being passed to your provider functions.

ERROR:flutter/lib/ui/ui_dart_state.cc(177) Unhandled Exception: NoSuchMethodError: The method 'insert' was called on null

Hello im a beginning flutter dev and i want to make a list with data from my cloud firestore database. I dont have any clue how should i do it. any help or advices about my code would be muchly appreciated
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dinghy1/components/default_button.dart';
import 'package:dinghy1/services/reservations.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../../../constants.dart';
import '../../../size_config.dart';
class Body extends StatefulWidget {
#override
_BodyState createState() => _BodyState();
}
class _BodyState extends State<Body> {
static List<Map<String, dynamic>> reservations;
static Map<String, dynamic> documents;
static List<QueryDocumentSnapshot> documents2;
static int index;
bool visibility = false;
String rental = ReservationService.rental;
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: SafeArea(
child: Column(
children: [
SizedBox(
height: getPropotionateScreenWidth(20),
),
Padding(
padding: EdgeInsets.symmetric(
horizontal: getPropotionateScreenWidth(20)),
child: Container(
decoration: BoxDecoration(
color: kPrimaryColor.withOpacity(0.4),
borderRadius: BorderRadius.circular(30)),
height: getPropotionateScreenHeight(75),
width: double.infinity,
child: Center(
child: Text(
"Sprawdź rezerwacje",
style: TextStyle(
fontSize: getPropotionateScreenWidth(20),
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
),
),
),
SizedBox(
height: getPropotionateScreenWidth(20),
),
DatePicker(),
SizedBox(
height: getPropotionateScreenWidth(20),
),
Padding(
padding: EdgeInsets.symmetric(
horizontal: getPropotionateScreenWidth(20)),
child: DefaultButton(
text: "Sprawdź",
press: () {
final FirebaseAuth auth = FirebaseAuth.instance;
final User user = auth.currentUser;
String uid = user.uid;
FirebaseFirestore.instance
.collection("users")
.doc(uid)
.get()
.then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
rental = documentSnapshot['rental'].toString();
ReservationService()
.getReservations(
rental,
_DatePickerState.selectedDate
.toString()
.split(" ")[0])
.then((QuerySnapshot docs) {
if (docs.docs.isNotEmpty) {
int i = 0;
index = docs.size - 1;
print(index);
while (i <= index) {
documents = docs.docs[i].data();
if (documents != null) {
reservations.insert(i, documents);
i++;
print(documents);
}
}
}
});
}
});
setState(() {
RentCard.name = documents['name'];
visibility = true;
});
},
),
),
SizedBox(
height: getPropotionateScreenWidth(20),
),
visibility == true
? new Padding(
padding: EdgeInsets.symmetric(
horizontal: getPropotionateScreenWidth(20)),
child: Column(
children: [
// ...List.generate(
// documents2.length,
// (index) => RentCard(reservations: reservations[0]),
// ),
],
),
)
: new Text(
'Wybierz date i naciśnij przycisk aby sprawdzić rezerwacje!')
],
),
),
);
}
}
Here's the code sample that is making an error
E/flutter ( 5082): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method 'insert' was called on null.
E/flutter ( 5082): Receiver: null
E/flutter ( 5082): Tried calling: insert(0, _LinkedHashMap len:7)
E/flutter ( 5082): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter ( 5082): #1 _BodyState.build.<anonymous closure>.<anonymous closure>.<anonymous closure>
package:dinghy1/…/components/body.dart:89
E/flutter ( 5082): #2 _rootRunUnary (dart:async/zone.dart:1198:47)
E/flutter ( 5082): #3 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 5082): #4 _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
E/flutter ( 5082): #5 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
E/flutter ( 5082): #6 Future._propagateToListeners (dart:async/future_impl.dart:725:32)
E/flutter ( 5082): #7 Future._completeWithValue (dart:async/future_impl.dart:529:5)
E/flutter ( 5082): #8 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:40:15)
E/flutter ( 5082): #9 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:311:13)
E/flutter ( 5082): #10 Query.get (package:cloud_firestore/src/query.dart)
package:cloud_firestore/src/query.dart:1
E/flutter ( 5082): <asynchronous suspension>
E/flutter ( 5082): #11 ReservationService.getReservations
package:dinghy1/services/reservations.dart:19
E/flutter ( 5082): #12 _BodyState.build.<anonymous closure>.<anonymous closure>
package:dinghy1/…/components/body.dart:76
E/flutter ( 5082): #13 _rootRunUnary (dart:async/zone.dart:1198:47)
E/flutter ( 5082): #14 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 5082): #15 _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
E/flutter ( 5082): #16 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
E/flutter ( 5082): #17 Future._propagateToListeners (dart:async/future_impl.dart:725:32)
E/flutter ( 5082): #18 Future._completeWithValue (dart:async/future_impl.dart:529:5)
E/flutter ( 5082): #19 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:40:15)
E/flutter ( 5082): #20 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:311:13)
E/flutter ( 5082): #21 DocumentReference.get (package:cloud_firestore/src/document_reference.dart)
package:cloud_firestore/src/document_reference.dart:1
E/flutter ( 5082): <asynchronous suspension>
E/flutter ( 5082): #22 _BodyState.build.<anonymous closure>
package:dinghy1/…/components/body.dart:71
E/flutter ( 5082): #23 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:993
E/flutter ( 5082): #24 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:1111
E/flutter ( 5082): #25 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:183
E/flutter ( 5082): #26 TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:598
E/flutter ( 5082): #27 BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:287
E/flutter ( 5082): #28 BaseTapGestureRecognizer.handlePrimaryPointer
package:flutter/…/gestures/tap.dart:222
E/flutter ( 5082): #29 PrimaryPointerGestureRecognizer.handleEvent
package:flutter/…/gestures/recognizer.dart:476
E/flutter ( 5082): #34 PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:106
E/flutter ( 5082): #35 GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:358
E/flutter ( 5082): #36 GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:338
E/flutter ( 5082): #37 RendererBinding.dispatchEvent
package:flutter/…/rendering/binding.dart:267
E/flutter ( 5082): #38 GestureBinding._handlePointerEvent
package:flutter/…/gestures/binding.dart:295
E/flutter ( 5082): #39 GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:240
E/flutter ( 5082): #40 GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:213
E/flutter ( 5082): #41 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 5082): #42 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 5082): #43 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 5082): #44 _invoke1 (dart:ui/hooks.dart:265:10)
E/flutter ( 5082): #45 _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)
E/flutter ( 5082):
Here's an error message.
If someone could help me fix that, i would went insane from happiness
In dart, we define lists and maps like this:
static List<Map<String, dynamic>> reservations = [];
static Map<String, dynamic> documents = {};
List<QueryDocumentSnapshot> documents2 = [];
If you want to learn more, read this topic about lists in dart.
Maps are mostly the same.

Error BLOC state [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: UnimplementedError

first of all, i got an error look like this
I/flutter ( 3245): BLOC Start
I/flutter ( 3245): BLOC Start
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building BlocBuilder<StationBloc, StationState>(dirty, state: _BlocBuilderBaseState<StationBloc, StationState>#24ede):
The getter 'length' was called on null.
Receiver: null
Tried calling: length
The relevant error-causing widget was:
BlocBuilder<StationBloc, StationState> file:///C:/Users/junia/FlutterApp/airportstation/airport_station/lib/view/home_screen.dart:42:18
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _HomeScreenState.buildStationList (package:airport_station/view/home_screen.dart:79:30)
#2 _HomeScreenState.build.<anonymous closure> (package:airport_station/view/home_screen.dart:51:24)
#3 BlocBuilder.build (package:flutter_bloc/src/bloc_builder.dart:90:57)
#4 _BlocBuilderBaseState.build (package:flutter_bloc/src/bloc_builder.dart:162:48)
Then, i went to stackoverflow and found a litte solution
Widget buildStationList(List<AllFlight> allFlight) {
return ListView.builder(
itemCount: allFlight.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
child: ListTile(
title: Text(allFlight[index].airportName + ' - ' + allFlight[index].countryName),
subtitle: Text(allFlight[index].label),
),
),
);
}
);
the problem is on itemCount: allFlight.length, and i change it into itemCount: allFlight?.length ?? 0,
after i run it again. there's still an error
I/flutter ( 3245): BLOC Start
I/flutter ( 3245): BLOC Start
E/flutter ( 3245): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: UnimplementedError
E/flutter ( 3245): #0 StationLoadedState.props (package:airport_station/bloc/station_state.dart:23:29)
E/flutter ( 3245): #1 Equatable.== (package:equatable/src/equatable.dart:50:18)
E/flutter ( 3245): #2 Bloc._bindEventsToStates.<anonymous closure> (package:bloc/src/bloc.dart:261:32)
E/flutter ( 3245): #3 _rootRunUnary (dart:async/zone.dart:1198:47)
E/flutter ( 3245): #4 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 3245): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 3245): #6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:357:11)
E/flutter ( 3245): #7 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:285:7)
E/flutter ( 3245): #8 _SyncBroadcastStreamController._sendData (dart:async/broadcast_stream_controller.dart:385:25)
E/flutter ( 3245): #9 _BroadcastStreamController._add (dart:async/broadcast_stream_controller.dart:293:5)
E/flutter ( 3245): #10 _rootRunUnary (dart:async/zone.dart:1198:47)
E/flutter ( 3245): #11 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 3245): #12 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 3245): #13 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:357:11)
E/flutter ( 3245): #14 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:285:7)
E/flutter ( 3245): #15 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:127:11)
E/flutter ( 3245): #16 _MapStream._handleData (dart:async/stream_pipe.dart:224:10)
E/flutter ( 3245): #17 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:157:13)
E/flutter ( 3245): #18 _rootRunUnary (dart:async/zone.dart:1198:47)
E/flutter ( 3245): #19 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 3245): #20 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 3245): #21 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:357:11)
E/flutter ( 3245): #22 _DelayedData.perform (dart:async/stream_impl.dart:611:14)
E/flutter ( 3245): #23 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:730:11)
E/flutter ( 3245): #24 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:687:7)
E/flutter ( 3245): #25 _rootRun (dart:async/zone.dart:1182:47)
E/flutter ( 3245): #26 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 3245): #27 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter ( 3245): #28 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter ( 3245): #29 _rootRun (dart:async/zone.dart:1190:13)
E/flutter ( 3245): #30 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 3245): #31 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter ( 3245): #32 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter ( 3245): #33 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter ( 3245): #34 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
E/flutter ( 3245):
my bloc_state.dart look like this
...
class StationLoadedState extends StationState {
final List<AllFlight> allFlight;
StationLoadedState({ #required this.allFlight });
#override
List<Object> get props => throw UnimplementedError();
}
...
and BlocBuilder
class _HomeScreenState extends State<HomeScreen> {
StationBloc stationBloc;
#override
void initState() {
super.initState();
stationBloc = BlocProvider.of(context);
stationBloc.add(FetchStationEvent());
}
...
body: Container(
child: BlocListener<StationBloc, StationState>(
listener: (context, state) {
if (state is StationErrorState) {
print(state.message);
}
},
child: BlocBuilder<StationBloc, StationState>(
builder: (context, state) {
print('BLOC Start');
if (state is StationInitialState) {
return buildLoading();
} else if (state is StationLoadingState) {
return buildLoading();
} else if (state is StationLoadedState) {
return buildStationList(state.allFlight);
} else if (state is StationErrorState) {
return buildError(state.message);
}
},
),
),
),
...
json response returned successfully when i try print it on http response. did someone know where the problem is?
BlocState has a "props" getter which should return an array of variables to compare states between each other. When you yield same state 2 times in a row, it will compare them using those props and if it's the same state as current - bloc will not yield it again (this is the default way it works when you're using Equatable).
In your code above you have this:
class StationLoadedState extends StationState {
final List<AllFlight> allFlight;
StationLoadedState({ #required this.allFlight });
#override
List<Object> get props => throw UnimplementedError();
}
It throws UnimplementedError when props are called. Change it to an array with your state's params.
class StationLoadedState extends StationState {
final List<AllFlight> allFlight;
StationLoadedState({ #required this.allFlight });
#override
List<Object> get props => [allFlight];
}

firebase phone number authentication is not working Unhandled Exception: PlatformException(error, null reference, null)

note: my both loginpage class and otpscreen class are statefulwidget i just avoid the extra code to show here.
i am trying to authenticate phone number. otp message is coming but not verfying after clicking the submit button here is the error i get
E/flutter (21679): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, null reference, null)
E/flutter (21679): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (21679): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:321:33)
E/flutter (21679): <asynchronous suspension>
E/flutter (21679): #2 MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:349:48)
E/flutter (21679): #3 MethodChannelFirebaseAuth.signInWithCredential (package:firebase_auth_platform_interface/src/method_channel_firebase_auth.dart:161:23)
E/flutter (21679): #4 FirebaseAuth.signInWithCredential (package:firebase_auth/src/firebase_auth.dart:208:10)
E/flutter (21679): #5 LoginRepository.signIn (package:doorstep/domain/repository/login-repository.dart:36:17)
E/flutter (21679): #6 OtpScreenState.submit.<anonymous closure> (package:doorstep/module/login/otpscreen.dart:90:26)
E/flutter (21679): #7 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (21679): #8 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (21679): #9 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (21679): #10 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (21679): #11 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (21679): #12 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:199:7)
E/flutter (21679): #13 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:467:9)
E/flutter (21679): #14 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (21679): #15 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:117:9)
E/flutter (21679): #16 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (21679): #17 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:115:18)
E/flutter (21679): #18 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:7)
E/flutter (21679): #19 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (21679): #20 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (21679): #21 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (21679): #22 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (21679): #23 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (21679): #24 _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (21679): #25 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (21679): #26 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (21679): #27 _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (21679): #28 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
This is loginrepository
class LoginRepository{
String verificationId;
var _auth = FirebaseAuth.instance;
Future<void> sendOtp(String _number) async {
final PhoneVerificationCompleted phoneVerificationCompleted =
(AuthCredential credential) {};
final PhoneVerificationFailed phoneVerificationFailed =
(AuthException exception) {
print("Login Faild due to $exception");
};
final PhoneCodeSent phoneCodeSent =
(String verificationId, [int forceResendingToken]) {
this.verificationId = verificationId;
};
final PhoneCodeAutoRetrievalTimeout phoneCodeAutoRetrievalTimeout =
(String verificationId) {
this.verificationId = verificationId;
print("time out");
};
await _auth.verifyPhoneNumber(
phoneNumber: _number,
timeout: Duration(seconds: 120),
verificationCompleted: phoneVerificationCompleted,
verificationFailed: phoneVerificationFailed,
codeSent: phoneCodeSent,
codeAutoRetrievalTimeout: phoneCodeAutoRetrievalTimeout);
}
Future<void> signIn(String otpCode) async {
final AuthCredential authCredential = PhoneAuthProvider.getCredential(
verificationId: verificationId, smsCode: otpCode);
await _auth.signInWithCredential(authCredential);
}
}
this is loginpage class
class LoginPage{
LoginRepository _loginRepository = LoginRepository();
Widget send() {
return FlatButton(
child: Text("Send OTP"),
onPressed: () {
_loginRepository.sendOtp(_numberController.text);
},
);
}
}
this is otp class
class OtpScreen{
LoginRepository _loginRepository = LoginRepository();
Widget submit() {
return FlatButton(
child: Text("Submit"),
onPressed: () async {
_loginRepository.signIn(_otpController.text);
},
);
}
}
This is happening due to the verificationId being null while reaching the manualPhoneAuth function. Somehow verification id is not getting assigned in the codeSent callback function.I changed the verificationId to a static variable and voila, It worked.
Change String verificationId to static String verificationId

Resources