This is a simple contact app that allows to add view and edit contact details of individuals. The error here can't be totally understood by me.
class ViewContact extends StatefulWidget {
final String id;
ViewContact(this.id);
#override
_ViewContactState createState() => _ViewContactState(this.id);
}
class _ViewContactState extends State<ViewContact> {
DatabaseReference _databaseReference = FirebaseDatabase.instance.reference();
String mascot = "https://learncodeonline.in/mascot.png";
String id;
_ViewContactState(id);
Contact _contact;
bool isLoading = true;
getContact(id) async {
_databaseReference.child(id).onValue.listen ((event){
setState(() {
print(event.snapshot);
_contact = Contact.fromSnapshot(event.snapshot);
isLoading = false;
print(_contact.lastName);
});
});
}
#override
void initState(){
super.initState();
this.getContact(id);
}
callAction(String number) async{
String url = 'tel: $number';
if (await canLaunch(url)){
await launch(url);
}
else {
throw 'Could call $number';
}
}
smsAction(String number) async{
String url ='sms: $number';
if (await canLaunch(url)){
await launch(url);
}
else {
throw 'lol';
}
}
navigateToLastScreen(){
Navigator.pop(context);
}
navigateToEditScreen(id){
Navigator.push(context, MaterialPageRoute(builder: (context){
return EditContact();
}));
}
The error shown is below. Can the error be because of the id variable? (Pretty new towards Flutter).
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'split' was called on null.
E/flutter (12369): Receiver: null
E/flutter (12369): Tried calling: split("/")
E/flutter (12369): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5)
E/flutter (12369): #1 DatabaseReference.child (package:firebase_database/src/database_reference.dart:24:58)
E/flutter (12369): #2 _ViewContactState.getContact (package:firebase_authentication/screens/view_contact.dart:24:25)
E/flutter (12369): <asynchronous suspension>
E/flutter (12369): #3 _ViewContactState.initState (package:firebase_authentication/screens/view_contact.dart:36:10)
E/flutter (12369): #4 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4033:58)
E/flutter (12369): #5 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3902:5)
E/flutter (12369): #6 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3084:14)
E/flutter (12369): #7 Element.updateChild (package:flutter/src/widgets/framework.dart:2887:12)
E/flutter (12369): #8 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5092:14)
E/flutter (12369): #9 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3084:14)
E/flutter (12369): #10 Element.updateChild (package:flutter/src/widgets/framework.dart:2887:12)
E/flutter (12369): #11 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3935:16)
E/flutter (12369): #12 Element.rebuild (package:flutter/src/widgets/framework.dart:3721:5)
E/flutter (12369): #13 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3907:5)
E/flutter (12369): #14 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3902:5)
E/flutter (12369): #15 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3084:14)
E/flutter (12369): #16 Element.updateChild (package:flutter/src/widgets/framework.dart:2887:12)
E/flutter (12369): #17 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5092:14)
E/flutter (12369): #18 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3084:14)
E/flutter (12369): #19 Element.updateChild (package:flutter/src/widgets/framework.dart:2887:12)
E/flutter (12369): #20 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5092:14)
E/flutter (12369): #21 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3084:14)
E/flutter (12369): #22 Element.updateChild (package:flutter/src/widgets/framework.dart:2887:12)
E/flutter (12369): #23 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5092:14)
E/flutter (12369): #24 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3084:14)
E/flutter (12369): #25 Element.updateChild (package:flutter/src/widgets/framework.dart:2887:12)
E/flutter (12369): #26 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5092:14)
E/flutter (12369): #27 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3084:14)
E/flutter (12369): #28 Element.updateChild (package:flutter/src/widgets/framework.dart:2887:12)
E/flutter (12369): #29 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3935:16)
E/flutter (12369): #30 Element.rebuild (package:flutter/src/widgets/framework.dart:3721:5)
E/flutter (12369): #31 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3907:5)
E/flutter (12369): #32 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4053:11)
E/flutter (12369): #33 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3902:5)
E/flutter (12369): #34 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3084:14)
E/flutter (12369): #35 Element.updateChild (package:flutter/src/widgets/framework.dart:2887:12)
E/flutter (12369): #36 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3935:16)
E/flutter (12369): #37 Element.rebuild (package:flutter/src/widgets/framework.dart:3721:5)
E/flutter (12369): #38 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3907:5)
E/flutter (12369): #39 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3902:5)
E/flutter (12369): #40 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3084:14)
E/flutter (12369): #41 Element.updateChild (package:flutter/src/widgets/framework.dart:2887:12)
E/flutter (12369): #42 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3935:16)
E/flutter (12369): #43 Element.rebuild (package:flutter/src/widgets/framework.dart:3721:5)
E/flutter (12369): #44 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart
this is the stack over flow error i am facing. Well same as the previous error , i can't figure out this one too :(
I/flutter ( 4594): The following StackOverflowError was thrown building ViewContact(dirty, state:
I/flutter ( 4594): _ViewContactState#4e21c):
I/flutter ( 4594): Stack Overflow
I/flutter ( 4594):
I/flutter ( 4594): When the exception was thrown, this was the stack:
I/flutter ( 4594): #0 Contact.email (package:firebase_authentication/model/contact.dart:25:4)
I/flutter ( 4594): #1 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #2 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #3 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #4 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #5 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #6 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #7 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #8 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #9 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #10 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #11 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #12 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #13 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #14 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #15 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #16 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #17 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #18 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #19 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #20 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #21 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #22 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #23 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #24 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #25 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #26 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #27 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #28 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #29 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #30 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #31 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #32 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #33 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #34 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #35 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #36 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #37 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #38 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #39 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #40 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #41 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #42 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #43 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): ...
I/flutter ( 4594): ...
I/flutter ( 4594): #59478 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59479 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59480 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59481 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59482 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59483 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59484 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59485 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59486 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59487 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59488 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59489 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59490 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59491 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59492 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59493 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59494 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59495 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59496 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59497 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59498 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59499 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59500 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59501 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59502 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59503 Contact.email (package:firebase_authentication/model/contact.dart:25:29)
I/flutter ( 4594): #59504 _ViewContactState.build (package:firebase_authentication/screens/view_contact.dart:179:40)
I/flutter ( 4594): #59505 StatefulElement.build (package:flutter/src/widgets/framework.dart:4012:27)
I/flutter ( 4594): #59506 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3924:15)
I/flutter ( 4594): #59507 Element.rebuild (package:flutter/src/widgets/framework.dart:3721:5)
I/flutter ( 4594): #59508 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2340:33)
I/flutter ( 4594): #59509 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
I/flutter ( 4594): #59510 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:285:5)
I/flutter ( 4594): #59511 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1016:15)
I/flutter ( 4594): #59512 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:958:9)
I/flutter ( 4594): #59513 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:874:5)
I/flutter ( 4594): #59517 _invoke (dart:ui/hooks.dart:236:10)
I/flutter ( 4594): #59518 _drawFrame (dart:ui/hooks.dart:194:3)
I/flutter ( 4594): (elided 3 frames from package dart:async)
================================================================================
This is the Widget Associated with the View Contact state.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Add Contact"),
centerTitle: true,
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: (){navigateToLastScreen(context);},
),
),
body: Container(
padding: EdgeInsets.all(20.0),
child: ListView(
children: <Widget>[
Container(
margin: EdgeInsets.only(top: 20.0),
child: GestureDetector(
onTap: (){
this.pickImage();
},
child: Center(
child: Container(
width: 130.0,
height: 130.0,
decoration: BoxDecoration(
border: Border.all(color: Colors.white, width: 4.0),
shape: BoxShape.circle,
image: DecorationImage(
fit: BoxFit.fill,
image: _photoUrl=="empty"? NetworkImage("https://i.imgur.com/BoN9kdC.png"): NetworkImage(_photoUrl),
),
),
),
),
),
),
Container(
margin: EdgeInsets.only(top: 40.0),
child: TextField(
onChanged: (value){
setState(() {
_firstName = value;
});
},
decoration: InputDecoration(
labelText: 'First Name',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
),
Container(
margin: EdgeInsets.only(top: 20.0),
child: TextField(
onChanged: (value){
setState(() {
_lastName = value;
});
},
decoration: InputDecoration(
labelText: 'Last Name',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
),
Container(
margin: EdgeInsets.only(top: 20.0),
child: TextField(
onChanged: (value){
setState(() {
_email = value;
});
},
decoration: InputDecoration(
labelText: 'E-mail',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
),
Container(
margin: EdgeInsets.only(top: 20.0),
child: TextField(
onChanged: (value){
setState(() {
_phone = value;
});
},
decoration: InputDecoration(
labelText: 'Phone',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
),
Container(
margin: EdgeInsets.only(top: 20.0),
child: TextField(
onChanged: (value){
setState(() {
_address = value;
});
},
decoration: InputDecoration(
labelText: 'Address',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
),
//save the shit
Container(
padding: EdgeInsets.only(top: 20.0),
child: RaisedButton(
color: Colors.teal,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
padding: EdgeInsets.fromLTRB(50, 10, 50, 10),
onPressed: (){
saveContact(context);
},
child: Text("ADD CONTACT", style: TextStyle(color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.bold),),
),
),
],
),
),
);
}
}
I believe the id is null.
E/flutter (12369): #2 _ViewContactState.getContact (package:firebase_authentication/screens/view_contact.dart:24:25)
Following the stacktrace, this line raises the exception:
_databaseReference.child(id).onValue.listen((event)
E/flutter (12369): #1 DatabaseReference.child (package:firebase_database/src/database_reference.dart:24:58)
from database_reference.dart line 19-25:
/// Gets a DatabaseReference for the location at the specified relative
/// path. The relative path can either be a simple child key (e.g. ‘fred’) or
/// a deeper slash-separated path (e.g. ‘fred/name/first’).
DatabaseReference child(String path) {
return DatabaseReference._(_database,
(List<String>.from(_pathComponents)..addAll(path.split('/'))));
}
path is your id, so I would say the id is null.
E/flutter (12369): Receiver: null
E/flutter (12369): Tried calling: split("/")
You can add assertion to the constructor, if id is null, an error will be thrown and you can then follow the stacktrace to find the broken code.
class ViewContact extends StatefulWidget {
final String id;
const ViewContact({Key key, #required this.id})
: assert(id != null),
super(key: key);
#override
_ViewContactState createState() => _ViewContactState(this.id);
}
EDIT:
#1
change this line:
_ViewContactState(id);
to
_ViewContactState(this.id);
the field id in the state will never be updated!
#2
you can access the id filed from the Widget class by calling widget.id
id will never be changed don't put it to the State constructor.
This should work
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
class ViewContact extends StatefulWidget {
final String id;
const ViewContact({Key key, #required this.id})
: assert(id != null),
super(key: key);
#override
_ViewContactState createState() => _ViewContactState();
}
class _ViewContactState extends State<ViewContact> {
final DatabaseReference _databaseReference = FirebaseDatabase.instance.reference();
final String mascot = "https://learncodeonline.in/mascot.png";
Contact _contact;
bool isLoading = true;
getContact(id) async {
_databaseReference.child(id).onValue.listen((event) {
setState(() {
print(event.snapshot);
_contact = Contact.fromSnapshot(event.snapshot);
isLoading = false;
print(_contact.lastName);
});
});
}
#override
void initState() {
super.initState();
this.getContact(widget.id);
}
callAction(String number) async {
String url = 'tel: $number';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could call $number';
}
}
smsAction(String number) async {
String url = 'sms: $number';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'lol';
}
}
navigateToLastScreen() {
Navigator.pop(context);
}
navigateToEditScreen(id) {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return EditContact();
}));
}
}
You should use
_ViewContactState(this.id);
in the constructor, to initialise id. Otherwise it will be null, and hence the error.
However you don't really need to pass it, as the StatefulWidget can access it through the widget. call
class ViewContact extends StatefulWidget {
final String id;
ViewContact(this.id);
#override
_ViewContactState createState() => _ViewContactState();
}
class _ViewContactState extends State<ViewContact> {
DatabaseReference _databaseReference = FirebaseDatabase.instance.reference();
String mascot = "https://learncodeonline.in/mascot.png";
_ViewContactState();
Contact _contact;
bool isLoading = true;
getContact(id) async {
_databaseReference.child(id).onValue.listen ((event){
setState(() {
print(event.snapshot);
_contact = Contact.fromSnapshot(event.snapshot);
isLoading = false;
print(_contact.lastName);
});
});
}
#override
void initState(){
super.initState();
this.getContact(widget.id);
}
Related
I'm trying to receive an OTP for user-authentication. But, I didn't receive any OTP, I'm getting this error.
Here is the error:
E/flutter (30379): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)]
Unhandled Exception: NoSuchMethodError: The getter 'instance' was
called on null. E/flutter (30379): Receiver: null E/flutter (30379):
Tried calling: instance E/flutter (30379): #0 Object.noSuchMethod
(dart:core-patch/object_patch.dart:54:5) E/flutter (30379): #1
_OtpscreenState.verifyPhone (package:userauth/Otpscreen.dart:172:24) E/flutter (30379): #2 _OtpscreenState.initState
(package:userauth/Otpscreen.dart:210:5) E/flutter (30379): #3
StatefulElement._firstBuild(package:flutter/src/widgets/framework.dart:4711:57)
E/flutter (30379): #4 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:4548:5) E/flutter (30379):
#5 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3611:14) E/flutter
(30379): #6 Element.updateChild
(package:flutter/src/widgets/framework.dart:3363:18) E/flutter
(30379): #7 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:6083:14) E/flutter
(30379): #8 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:3611:14) E/flutter
(30379): #9 Element.updateChild
(package:flutter/src/widgets/framework.dart:3363:18) E/flutter
(30379): #10 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4599:16) E/flutter
(30379): #11 Element.rebuild
(package:flutter/src/widgets/framework.dart:4267:5) E/flutter (30379):
#12 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4553:5) E/flutter (30379):
#13 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4548:5) E/flutter (30379):
#14 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3611:14) E/flutter
(30379): #15 Element.updateChild
(package:flutter/src/widgets/framework.dart:3363:18) E/flutter
(30379): #16 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:6083:14) E/flutter
(30379): #17 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:3611:14) E/flutter
(30379): #18 Element.updateChild
(package:flutter/src/widgets/framework.dart:3363:18) E/flutter
(30379): #19 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:6083:14) E/flutter
(30379): #20 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:3611:14) E/flutter
(30379): #21 Element.updateChild
(package:flutter/src/widgets/framework.dart:3363:18) E/flutter
(30379): #22 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4599:16) E/flutter
(30379): #23 StatefulElement.performRebuild
(package:flutter/src/widgets/framework.dart:4746:11) E/flutter
(30379): #24 Element.rebuild
(package:flutter/src/widgets/framework.dart:4267:5) E/flutter (30379):
#25 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4553:5) E/flutter (30379):
#26 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4737:11) E/flutter
(30379): #27 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:4548:5) E/flutter (30379):
#28 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3611:14) E/flutter
(30379): #29 Element.updateChild
(package:flutter/src/widgets/framework.dart:3363:18) E/flutter
(30379): #30 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:6083:14) E/flutter
(30379): #31 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:3611:14) E/flutter
(30379): #32 Element.updateChild
(package:flutter/src/widgets/framework.dart:3363:18) E/flutter
(30379): #33 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:6083:14) E/flutter
(30379): #34 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:3611:14) E/flutter
(30379): #35 Element.updateChild
(package:flutter/src/widgets/framework.dart:3363:18) E/flutter
(30379): #36 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4599:16) E/flutter
(30379): #37 StatefulElement.performRebuild
(package:flutter/src/widgets/framework.dart:4746:11) E/flutter
(30379): #38 Element.rebuild
(package:flutter/src/widgets/framework.dart:4267:5) E/flutter (30379):
#39 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4553:5) E/flutter (30379):
#40 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4737:11) E/flutter
(30379): #41 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:4548:5) E/flutter (30379):
#42 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3611:14) E/flutter
(30379): #43 Element.updateChild
(package:flutter/src/widgets/framework.dart:3363:18) E/flutter
(30379): #44 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4599:16)
Here is my code:
import 'package:flutter/material.dart';
import 'package:pinput/pin_put/pin_put.dart';
import 'package:pinput/pin_put/pin_put_state.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:userauth/Profilescreen.dart';
class Otpscreen extends StatefulWidget {
String phone;
Otpscreen(this.phone);
#override
_OtpscreenState createState() => _OtpscreenState();
}
class _OtpscreenState extends State<Otpscreen> {
final GlobalKey<ScaffoldState> _scaffoldkey = GlobalKey<ScaffoldState>();
late String otp;
late String _verificationCode;
final TextEditingController _pinPutController = TextEditingController();
final FocusNode _pinPutFocusNode = FocusNode();
final BoxDecoration pinPutDecoration = BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(10.0),
border: Border.all(
color: const Color.fromRGBO(126, 203, 224, 1),
),
);
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.only(top: 10, bottom: 10),
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(right: 310),
child: RawMaterialButton(
onPressed: () {
Navigator.pop(context, "phone");
},
child: Icon(Icons.arrow_back),
),
),
SizedBox(height: 40),
Text(
"Verify Phone",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.black),
),
SizedBox(height: 10),
Text(
"code is sent to ${widget.phone}",
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: Colors.grey),
),
Padding(
padding: const EdgeInsets.all(30.0),
child: PinPut(
fieldsCount: 6,
textStyle: const TextStyle(
fontSize: 25.0, color: Colors.white),
eachFieldWidth: 40.0,
eachFieldHeight: 55.0,
focusNode: _pinPutFocusNode,
controller: _pinPutController,
submittedFieldDecoration: pinPutDecoration,
selectedFieldDecoration: pinPutDecoration,
followingFieldDecoration: pinPutDecoration,
pinAnimationType: PinAnimationType.fade,
onSubmit: (pin) async {
try {
await FirebaseAuth.instance
.signInWithCredential(
PhoneAuthProvider.credential(
verificationId: _verificationCode,
smsCode: pin))
.then((value) async {
if (value.user != null) {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => Profilescreen()),
(route) => false);
}
});
} catch (e) {
FocusScope.of(context).unfocus();
_scaffoldkey.currentState!.showSnackBar(
SnackBar(content: Text("invalid OTP")));
}
},
),
),
SizedBox(
height: 20,
),
Center(
child: Padding(
padding: const EdgeInsets.only(
left: 20, right: 20, top: 0, bottom: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Text(
"Didn't receive an code?",
),
),
GestureDetector(
onTap: () {
Navigator.pushNamed(context, "phone");
},
child: Center(
child: Text(
"Request Again",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
),
),
],
),
),
),
SizedBox(height: 20),
RawMaterialButton(
onPressed: () {
Navigator.pushNamed(context, "profile");
},
fillColor: Colors.blue,
child: Padding(
padding: const EdgeInsets.fromLTRB(50, 15, 50, 15),
child: Text(
"VERIFY AND CONTINUE",
style: TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
),
),
),
],
),
),
),
],
),
),
);
}
verifyPhone() async {
var firebaseAuth;
var widget;
await firebaseAuth.instance.verifyPhoneNumber(
phoneNumber: "+91${widget.phone}",
verificationCompleted: (PhoneAuthCredential credential) async {
await firebaseAuth.instance
.signInCredential(credential)
.then((value) async {
if (value.user > 0) {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => Profilescreen()),
(route) => false);
}
});
},
verificationFailed: (FirebaseAuthException e) {
print(e.message);
},
codesent: (String verificationID, int resendToken) {
setState(() {
_verificationCode = verificationID;
});
},
codeAutoRetrievalTimeout: (String verificationID) {
setState(() {
var verificationCode = verificationID;
});
},
timeout: Duration(seconds: 60));
}
#override
void initState() {
// TODO: implement initState
super.initState();
verifyPhone();
}
}
Thank you!
Here is the error:
var firebaseAuth;
var widget;
await firebaseAuth.instance.verifyPhoneNumber(
phoneNumber: "+91${widget.phone}",
verificationCompleted: (PhoneAuthCredential credential) async {
await firebaseAuth.instance
firebaseAuth is not referencing any object, thus you get:
The getter 'instance' was called on null.
Therefore, remove the variable since it's not needed, and since property instance returns static FirebaseAuth, then you have to do the following:
var widget;
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: "+91${widget.phone}",
verificationCompleted: (PhoneAuthCredential credential) async {
await FirebaseAuth.instance
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.
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];
}
I have made a simple baby names project using firebase on flutter,
after successfully going throught the tutorial, the app gives this error : " package:firebase_demo/main.dart': Failed assertion: line 86 pos 16: 'map['votes] ! = null': is not true. "
Help for the same.
MY CODE -:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
final dummySnapshot = [
{"name": "Filip", "votes": 15},
{"name": "Abraham", "votes": 14},
{"name": "Richard", "votes": 11},
{"name": "Ike", "votes": 10},
{"name": "Justin", "votes": 1},
];
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Baby Names',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() {
return _MyHomePageState();
}
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Baby Name Votes')),
body: _buildBody(context),
);
}
Widget _buildBody(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('baby').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return LinearProgressIndicator();
return _buildList(context, snapshot.data.documents);
},
);
}
Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
return ListView(
padding: const EdgeInsets.only(top: 20.0),
children: snapshot.map((data) => _buildListItem(context, data)).toList(),
);
}
Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
final record = Record.fromSnapshot(data);
return Padding(
key: ValueKey(record.name),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: ListTile(
title: Text(record.name),
trailing: Text(record.votes.toString()),
onTap: () => print(record),
),
),
);
}
}
class Record {
final String name;
final int votes;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map, {this.reference})
: assert(map['name'] != null),
assert(map['votes'] != null),
name = map['name'],
votes = map['votes'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
#override
String toString() => "Record<$name:$votes>";
}
Output :
Performing hot restart...
Syncing files to device Redmi Note 4...
Restarted application in 1,994ms.
I/flutter ( 2257): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 2257): The following assertion was thrown building StreamBuilder(dirty, state:
I/flutter ( 2257): _StreamBuilderBaseState>#94c3a):
I/flutter ( 2257): 'package:firebase_demo/main.dart': Failed assertion: line 86 pos 16: 'map['votes'] != null': is not
I/flutter ( 2257): true.
I/flutter ( 2257):
I/flutter ( 2257): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 2257): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 2257): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 2257): https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 2257):
I/flutter ( 2257): When the exception was thrown, this was the stack:
I/flutter ( 2257): #2 new Record.fromMap (package:firebase_demo/main.dart:86:16)
I/flutter ( 2257): #3 new Record.fromSnapshot (package:firebase_demo/main.dart:91:14)
I/flutter ( 2257): #4 _MyHomePageState._buildListItem (package:firebase_demo/main.dart:59:27)
I/flutter ( 2257): #5 _MyHomePageState._buildList. (package:firebase_demo/main.dart:54:40)
I/flutter ( 2257): #6 MappedListIterable.elementAt (dart:_internal/iterable.dart:414:29)
I/flutter ( 2257): #7 ListIterable.toList (dart:_internal/iterable.dart:219:19)
I/flutter ( 2257): #8 _MyHomePageState._buildList (package:firebase_demo/main.dart:54:71)
I/flutter ( 2257): #9 _MyHomePageState._buildBody. (package:firebase_demo/main.dart:46:16)
I/flutter ( 2257): #10 StreamBuilder.build (package:flutter/src/widgets/async.dart:423:74)
I/flutter ( 2257): #11 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
I/flutter ( 2257): #12 StatefulElement.build (package:flutter/src/widgets/framework.dart:3809:27)
I/flutter ( 2257): #13 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3721:15)
I/flutter ( 2257): #14 Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 2257): #15 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2286:33)
I/flutter ( 2257): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:676:20)
I/flutter ( 2257): #17 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 2257): #18 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 2257): #19 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 2257): #20 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
I/flutter ( 2257): #21 _invoke (dart:ui/hooks.dart:154:13)
I/flutter ( 2257): #22 _drawFrame (dart:ui/hooks.dart:143:3)
I/flutter ( 2257): (elided 2 frames from class _AssertionError)
I/flutter ( 2257): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/1.gpu ( 2257): type=1400 audit(0.0:191179): avc: denied { ioctl } for path="/dev/kgsl-3d0" dev="tmpfs" ino=15394 ioctlcmd=945 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:device:s0 tclass=chr_file permissive=1
I/1.gpu ( 2257): type=1400 audit(0.0:191180): avc: denied { read write } for path="/dev/kgsl-3d0" dev="tmpfs" ino=15394 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:device:s0 tclass=chr_file permissive=1
I/an.firebasedem( 2257): Waiting for a blocking GC ProfileSaver
I/an.firebasedem( 2257): WaitForGcToComplete blocked ProfileSaver on ProfileSaver for 30.771ms
Maybe you can check your collection name in the firebase first.
stream: Firestore.instance.collection('your_collection_name_here').snapshots(),
Make sure your fields in the Firebase match with the proprieties of Record.
e.g:
name matches name field from the database
votes matches votes field from the database
I am having trouble finding the source to this exception, and the app is quite complex so it is hard to show any relevant part of the code. This is my repository at the point where the error happens:
Github repo
I suspect the following code might be the perpetrator:
Widget buildResultCard(Map result, BuildContext context) {
String name = result["value"];
String description =
result["label"].replaceAll(new RegExp(r"<(?:.|\n)*?>"), "");
TextEditingController controller = new TextEditingController(text: name);
Function onPressed = () {
showDialog(
context: context,
child: new AlertDialog(
title: new Text("Name your schedule"),
content: new TextField(
autofocus: true,
controller: controller,
),
actions: <Widget>[
new FlatButton(
onPressed: () {
String givenName = controller.text;
ScheduleMeta schedule = new ScheduleMeta(
givenName: givenName,
name: name,
type: _selectedChoice.value,
description: description);
scheduleStore
.dispatch(new AddScheduleAction(schedule: schedule));
scheduleStore.dispatch(
new SetCurrentScheduleAction(schedule: schedule));
fetchAllSchedules(scheduleStore.state.schedules)
.then((weeks) {
scheduleStore.dispatch(
new SetWeeksForCurrentScheduleAction(weeks: weeks));
});
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text("Added " + givenName),
action: new SnackBarAction(
label: "Undo",
onPressed: () {
scheduleStore.dispatch(
new RemoveScheduleAction(schedule: name));
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text(
"Deleted " + givenName),
));
}),
));
Navigator.of(context).pop();
},
child: new Text("Add")),
],
));
};
return new Card(
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new ListTile(
leading: const Icon(Icons.schedule),
title: new Text(name),
subtitle: new Text(description),
isThreeLine: true,
dense: true,
),
new ButtonTheme.bar(
child: new ButtonBar(
children: <Widget>[
new FlatButton(
child: const Text('Add Schedule'),
onPressed: scheduleStore.state.schedules
.any((schedule) => schedule.name == name)
? null
: onPressed)
],
),
),
],
),
);
}
The error appears when showing a dialog, and when the user presses a button on the dialog, two Redux store dispatches are sent directly after each other. The UI behind the dialog subscribes to changes in the Redux store.
I thought Dart/Flutter was single-threaded so no collision like this could happen, where it seems like a thread is calling setState() on a widget while another has put a lock on the widget tree.
Is there a way of checking if the widget tree is locked so this can be avoided?
The stack provides this info:
I/flutter (13466): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (13466): The following assertion was thrown while finalizing the widget tree:
I/flutter (13466): setState() or markNeedsBuild() called when widget tree was locked.
I/flutter (13466): This _ModalScope widget cannot be marked as needing to build because the framework is locked.
I/flutter (13466): The widget on which setState() or markNeedsBuild() was called was:
I/flutter (13466): _ModalScope([LabeledGlobalKey<_ModalScopeState>#cb4cc]; state: _ModalScopeState#d4c02())
I/flutter (13466):
I/flutter (13466): When the exception was thrown, this was the stack:
I/flutter (13466): #0 Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:3250)
I/flutter (13466): #2 Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:3226)
I/flutter (13466): #3 State.setState (package:flutter/src/widgets/framework.dart:1072)
I/flutter (13466): #4 _ModalScopeState._routeSetState (package:flutter/src/widgets/routes.dart:473)
I/flutter (13466): #5 ModalRoute.setState (package:flutter/src/widgets/routes.dart:552)
I/flutter (13466): #6 ModalRoute.changedInternalState (package:flutter/src/widgets/routes.dart:889)
I/flutter (13466): #7 TransitionRoute&&LocalHistoryRoute.removeLocalHistoryEntry (package:flutter/src/widgets/routes.dart:317)
I/flutter (13466): #8 LocalHistoryEntry.remove (package:flutter/src/widgets/routes.dart:267)
I/flutter (13466): #9 DrawerControllerState.dispose (package:flutter/src/material/drawer.dart:147)
I/flutter (13466): #10 StatefulElement.unmount (package:flutter/src/widgets/framework.dart:3550)
I/flutter (13466): #11 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1626)
I/flutter (13466): #12 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1624)
I/flutter (13466): #13 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3427)
I/flutter (13466): #14 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1622)
I/flutter (13466): #15 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1624)
I/flutter (13466): #16 MultiChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:4421)
I/flutter (13466): #17 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1622)
I/flutter (13466): #18 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1624)
I/flutter (13466): #19 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3427)
I/flutter (13466): #20 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1622)
I/flutter (13466): #21 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1624)
I/flutter (13466): #22 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3427)
I/flutter (13466): #23 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1622)
I/flutter (13466): #24 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1624)
I/flutter (13466): #25 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:4321)
I/flutter (13466): #26 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1622)
I/flutter (13466): #27 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1624)
I/flutter (13466): #28 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3427)
I/flutter (13466): #29 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1622)
I/flutter (13466): #30 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1624)
I/flutter (13466): #31 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:4321)
I/flutter (13466): #32 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1622)
I/flutter (13466): #33 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1624)
I/flutter (13466): #34 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3427)
I/flutter (13466): #35 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1622)
I/flutter (13466): #36 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1624)
I/flutter (13466): #37 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3427)
I/flutter (13466): #38 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1622)
I/flutter (13466): #39 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1624)
I/flutter (13466): #40 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3427)
I/flutter (13466): #41 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1622)
I/flutter (13466): #42 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1624)
I/flutter (13466): #43 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3427)
I/flutter (13466): #44 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1622)
I/flutter (13466): #45 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1624)
I/flutter (13466): #46 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3427)
I/flutter (13466): #47 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1622)
I/flutter (13466): #48 _InactiveElements._unmountAll (package:flutter/src/widgets/framework.dart:1636)
I/flutter (13466): #49 BuildOwner.finalizeTree.<anonymous closure> (package:flutter/src/widgets/framework.dart:2228)
I/flutter (13466): #50 BuildOwner.lockState (package:flutter/src/widgets/framework.dart:2060)
I/flutter (13466): #51 BuildOwner.finalizeTree (package:flutter/src/widgets/framework.dart:2227)
I/flutter (13466): #52 BindingBase&SchedulerBinding&GestureBinding&ServicesBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:505)
I/flutter (13466): #53 BindingBase&SchedulerBinding&GestureBinding&ServicesBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:189)
I/flutter (13466): #54 BindingBase&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:688)
I/flutter (13466): #55 BindingBase&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:636)
I/flutter (13466): #56 _drawFrame (file:///b/build/slave/Linux_Engine/build/src/flutter/lib/ui/hooks.dart:70)
I/flutter (13466): (elided one frame from class _AssertionError)
I/flutter (13466): ════════════════════════════════════════════════════════════════════════════════════════════════════
As a workaround wrap your code that calling setState into WidgetsBinding.addPostFrameCallback:
WidgetsBinding.instance
.addPostFrameCallback((_) => setState(() {}));
That way you can be sure it gets executed after the current widget is built.
Special case of using Scaffold and Drawer:
That fail can also happen if you try to rebuild the tree with opened Drawer. For example if you send a message to a Bloc that forces rebuilding of the whole page/screen.
Consider to call Navigator.pop(context) first in your tap handler.
This is not a thread problem. This error means that you are calling setState during the build phase.
A typical example would be the following :
Widget build(BuildContext context) {
myParentWidgetState.setState(() { print("foo"); });
return Container();
}
But the setState call may be less obvious. For example a Navigator.pop(context) does a setState internally. So the following :
Widget build(BuildContext context) {
Navigator.pop(context);
return Container();
}
is a no go either.
Looking at the stacktrace it seems that simultaneously with the Navigator.pop(context) your modal try to update with new data.
As the provided answer seems true, I had a work around as, in my case, it was not possible to simply remove it from the build.
I used Future.delayed(Duration.zero, () => setState(() { ... })); instead of setState and the same for methods that may use setState as well.
EDIT: source
There are couple of options used setState inside build method and context on initState
Wrap your setState inside one of these
WidgetsBinding.instance.addPostFrameCallback or Future.microTask() or Timer.run or Future.delayed(Duration.zero,
Example:
WidgetsBinding.instance
.addPostFrameCallback((_) {
//valueNotifier.value = _pcm; //provider
//setState
});
I faced the same issue when making a widget that need to do Navigator.pop before returning an Widget in build.
Let me call the code from Rémi Rousselet:
Widget build(BuildContext context) {
Navigator.pop(context);
return Container();
}
This code above would cause the error, but you could only pop becasue context is in build, so how to do?
Widget build(BuildContext context) {
if(datas != null) // check datas
{
SchedulerBinding.instance.addPostFrameCallback((_){ // make pop action to next cycle
Navigator.of(context).pop(datas); /*...your datas*/
});
}
return Container();
}
This method is the combination of the others, but I'm not sure If this is the best practice, If there are any errors, please leave a comment to point me out!
Use Timer class,
import 'dart:async';
#override
void initState() {
super.initState();
Timer.run(() {
// You can call setState from here
});
}
I control user at LoginScreen on every opening or reload. If user is authenticated i navigate to home. At this point i get same error. It's about navigator's own setState as i understood. addPostFrameCallback or timer fix it.
void initState() {
super.initState();
if (auth.getUser != null) {
// ERROR
// Navigator.pushReplacementNamed(context, '/home');
// SUCCESS
// WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {
// Navigator.pushReplacementNamed(context, '/home');
// }));
// SUCCESS
Timer.run(() {
Navigator.pushReplacementNamed(context, '/home');
});
}
}
void initState() {
super.initState();
if (auth.getUser != null) {
// ERROR
// Navigator.pushReplacementNamed(context, '/home');
// SUCCESS
// WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {
// Navigator.pushReplacementNamed(context, '/home');
// }));
// SUCCESS
Timer.run(() {
Navigator.pushReplacementNamed(context, '/home');
});
}
}