Flutter setState() or markNeedsBuild() called when widget tree was locked - redux

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

Related

Flutter Stackoverflow Error when using Firebase

I don't know where this Stackoverflow Error comes from
I/flutter (20342): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (20342): The following StackOverflowError was thrown building Analytics(dirty):
I/flutter (20342): Stack Overflow
I/flutter (20342):
I/flutter (20342): The relevant error-causing widget was:
I/flutter (20342): Analytics
I/flutter (20342): file:///C:/Users/OneDrive/Dokumente/Development/GitHub/trimlog/src/flutter_app/lib/screens/wrapper.dart:87:11
I/flutter (20342):
I/flutter (20342): When the exception was thrown, this was the stack:
I/flutter (20342): #0 _LinkedHashMapMixin._getValueOrData (dart:collection-patch/compact_hash.dart:331:3)
I/flutter (20342): #1 _LinkedHashMapMixin.containsKey (dart:collection-patch/compact_hash.dart:355:54)
I/flutter (20342): #2 FirebaseFirestore.instanceFor (package:cloud_firestore/src/firestore.dart:50:26)
I/flutter (20342): #3 new Database (package:Trimlog/services/database/database.dart:39:97)
I/flutter (20342): #4 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #5 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #6 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #7 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #8 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #9 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #10 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #11 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #12 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #13 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #14 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #15 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #16 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #17 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #18 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #19 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #20 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #21 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #22 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #23 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #24 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #25 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #26 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #27 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #28 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #29 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #30 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #31 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #32 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #33 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #34 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #35 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #36 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #37 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #38 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #39 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #40 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #41 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #42 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): #43 new Database (package:Trimlog/services/database/database.dart)
I/flutter (20342): ...
I/flutter (20342): ...
I/flutter (20342): #15600 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4606:5)
I/flutter (20342): #15601 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4791:11)
I/flutter (20342): #15602 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5)
I/flutter (20342): ... Normal element mounting (7 frames)
I/flutter (20342): #15609 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
I/flutter (20342): #15610 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
I/flutter (20342): #15611 SliverMultiBoxAdaptorElement.updateChild (package:flutter/src/widgets/sliver.dart:1158:36)
I/flutter (20342): #15612 SliverMultiBoxAdaptorElement.createChild.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1143:20)
I/flutter (20342): #15613 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2683:19)
I/flutter (20342): #15614 SliverMultiBoxAdaptorElement.createChild (package:flutter/src/widgets/sliver.dart:1136:11)
I/flutter (20342): #15615 RenderSliverMultiBoxAdaptor._createOrObtainChild.<anonymous closure> (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:350:23)
I/flutter (20342): #15616 RenderObject.invokeLayoutCallback.<anonymous closure> (package:flutter/src/rendering/object.dart:1883:59)
I/flutter (20342): #15617 PipelineOwner._enableMutationsToDirtySubtrees (package:flutter/src/rendering/object.dart:915:15)
I/flutter (20342): #15618 RenderObject.invokeLayoutCallback (package:flutter/src/rendering/object.dart:1883:14)
I/flutter (20342): #15619 RenderSliverMultiBoxAdaptor._createOrObtainChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:339:5)
I/flutter (20342): #15620 RenderSliverMultiBoxAdaptor.insertAndLayoutChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:485:5)
I/flutter (20342): #15621 RenderSliverFixedExtentBoxAdaptor.performLayout (package:flutter/src/rendering/sliver_fixed_extent_list.dart:259:17)
I/flutter (20342): #15622 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7)
I/flutter (20342): #15623 RenderSliverEdgeInsetsPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:132:12)
I/flutter (20342): #15624 _RenderSliverFractionalPadding.performLayout (package:flutter/src/widgets/sliver_fill.dart:170:11)
I/flutter (20342): #15625 RenderObject.layout (package:flutter/src/rendering/object.dart:1777:7)
I/flutter (20342): #15626 RenderViewportBase.layoutChildSequence (package:flutter/src/rendering/viewport.dart:507:13)
I/flutter (20342): #15627 RenderViewport._attemptLayout (package:flutter/src/rendering/viewport.dart:1561:12)
I/flutter (20342): #15628 RenderViewport.performLayout (package:flutter/src/rendering/viewport.dart:1470:20)
I/flutter (20342): #15629 RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1634:7)
I/flutter (20342): #15630 PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:884:18)
I/flutter (20342): #15631 RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:436:19)
I/flutter (20342): #15632 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:914:13)
I/flutter (20342): #15633 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:302:5)
I/flutter (20342): #15634 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15)
I/flutter (20342): #15635 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1055:9)
I/flutter (20342): #15636 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:971:5)
I/flutter (20342): #15640 _invoke (dart:ui/hooks.dart:251:10)
I/flutter (20342): #15641 _drawFrame (dart:ui/hooks.dart:209:3)
I/flutter (20342): (elided 3 frames from dart:async)
I/flutter (20342):
I/flutter (20342): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter (20342): Another exception was thrown: NoSuchMethodError: The getter 'analytic' was called on null.
In my main.dart
class Instances {
static Database database = new Database();
}
In database.dart
class Database {
final _databaseReference = FirebaseFirestore.instance; // Instance of Firebase
final user = new DatabaseUser();
final boat = new DatabaseBoat();
final trim = new DatabaseTrim();
final analytic = new DatabaseAnalytic();
In database_analytic.dart
class DatabaseAnalytic extends Database {
How I access for example DatabaseAnalytic
Instances.database.analytic.deleteAnalyticOfBoat(widget.boat.documentid, widget.analytic.documentid)
wrapper.dart: https://hastebin.com/eholocelug.java
Can someone tell me where the error comes from?
I have seen, that it says "The getter 'analytic' was called on null.", but I cannot figure out why that is.
I am also not sure whether this is the best way to work with the Database, if there is a better way it would be great if you let me know.
We can see this in your error output
Another exception was thrown: NoSuchMethodError: The getter 'analytic' was called on null.
With this line
Instances.database.analytic.deleteAnalyticOfBoat(widget.boat.documentid,widget.analytic.documentid)
Your error assumes that Instances.database is null
If you look at the rest of the error, Database is constantly being instantiated over and over again. Database is instantiating DatabaseAnalytic which is instantiating Database again. It's what is causing an overflow error.

Getting error when using multiprovider and consumer in flutter

I recently updated firebase dependencies. I do not recommend this, by the way, I am having an awful experience. Google can't figure out what naming conventions to go by.
after updating and fixing all of the errors they caused I tried to run my app and got the initialize firebase error. Well after that error was mitigated I seem to have run into an error I cannot solve.
Here is the relevant code.
Widget build(BuildContext context) {
return StreamProvider<UserTutor>.value(
value: AuthService().user,
child: Consumer<UserTutor>(
builder: (_, user, __) {
return MultiProvider(
providers: [
user == null
? StreamProvider<Tutor>.value(
value: DatabaseService().streamTutor,
)
: StreamProvider<Tutor>.value(
value: DatabaseService(uid: user.uid).streamTutor,
),
user == null
? StreamProvider<List<ClassData>>.value(
value: DatabaseService().classdata)
: StreamProvider<List<ClassData>>.value(
value: DatabaseService(uid: user.uid).classdata),
],
child: MaterialApp(
home: Wrapper(),
debugShowCheckedModeBanner: false,
),
);
},
));
}
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
//create user obj based on firebase user
UserTutor _userFromFirebaseUser(User user) {
return user != null ? UserTutor(uid: user.uid, email: user.email) : null;
}
//auth change user stream
Stream<UserTutor> get user {
return _auth
.authStateChanges()
.map((User user) => _userFromFirebaseUser(user));
}
and here is the error I am receiving.
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building Consumer<UserTutor>(dirty, dependencies:
flutter: [_InheritedProviderScope<UserTutor>]):
flutter: a collection path must point to a valid collection.
flutter: 'package:cloud_firestore/src/firestore.dart':
flutter: Failed assertion: line 74 pos 12: 'isValidCollectionPath(collectionPath)'
flutter:
flutter: The relevant error-causing widget was:
flutter: Consumer<UserTutor>
flutter: file:///Users/devintripp/Desktop/flutter_apps.no_sync/discoverytutors/lib/main.dart:25:16
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #2 FirebaseFirestore.collection (package:cloud_firestore/src/firestore.dart:74:12)
flutter: #3 new DatabaseService (package:disc_t/Services/database.dart:19:34)
flutter: #4 MyApp.build.<anonymous closure> (package:disc_t/main.dart:37:32)
flutter: #5 Consumer.buildWithChild (package:provider/src/consumer.dart:175:19)
flutter: #6 SingleChildStatelessWidget.build (package:nested/nested.dart:260:41)
flutter: #7 StatelessElement.build (package:flutter/src/widgets/framework.dart:4620:28)
flutter: #8 SingleChildStatelessElement.build (package:nested/nested.dart:280:18)
flutter: #9 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
flutter: #10 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
flutter: #11 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)
flutter: #12 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5)
flutter: #13 SingleChildWidgetElementMixin.mount (package:nested/nested.dart:223:11)
flutter: #14 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
flutter: #15 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
flutter: #16 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
flutter: #17 _InheritedProviderScopeElement.performRebuild (package:provider/src/inherited_provider.dart:426:11)
flutter: #18 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
flutter: #19 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)
flutter: #20 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5)
flutter: ... Normal element mounting (7 frames)
flutter: #27 SingleChildWidgetElementMixin.mount (package:nested/nested.dart:223:11)
flutter: ... Normal element mounting (7 frames)
flutter: #34 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
flutter: #35 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
flutter: #36 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1174:16)
flutter: #37 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1145:5)
flutter: #38 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1087:17)
flutter: #39 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2620:19)
flutter: #40 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1086:13)
flutter: #41 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:927:7)
flutter: #42 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:908:7)
flutter: (elided 13 frames from class _AssertionError, class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
flutter:

Stream.asFuture() duplicating data when widget is refreshed

When i first load the widget it gives me an error but works as expected. When I go to another screen then back though it will duplicated the data from the future.
#override
Widget build(BuildContext context) {
final userdata = context.watch<UserDataNotifier>();
UserData data = Provider.of<UserData>(context);
double h = MediaQuery.of(context).size.height;
// print(data);
return StreamBuilder(
stream: Stream.fromFuture(data.getTheUserClasses),
builder: (context, snapshot) {
snapshot.data.toString();
return Scaffold(
backgroundColor: Color(0xff3DDC97),
appBar: AppBar(
backgroundColor: Color(0xff7211E0),
title: userdata.user == null
? CircularProgressIndicator()
: Text(userdata.user.firstName ?? ""),
),
body: Container(
// padding: EdgeInsets.symmetric(vertical: h / 8),
padding: EdgeInsets.fromLTRB(0, h / 8, 0, 0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(
height: h * .5,
child: data.classList == null
? Loading()
: data.classList.isEmpty
? Loading()
: UserClassList(
data: data.classList,
)),
RaisedButton(
child: Text("Add Class"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PickFromAllClasses()))
.then((value) => value ? _refresh() : null);
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Colors.blue,
)
],
)),
);
},
);
}
here is how I get the data
class UserData {
String uid;
String firstName;
int rating;
List<String> classes;
List<ClassData> classList = List<ClassData>();
UserData.fromMap(Map<String, dynamic> data) {
firstName = data['firstname'] ?? "";
rating = data['rating'] ?? "";
classes = data['classes'].cast<String>() ?? "";
}
List<ClassData> get cs => classList;
set cs(List<ClassData> s) {
cs = s;
}
Future get getTheUserClasses async {
for (String c in classes) {
DocumentSnapshot classsnapshot =
await Firestore.instance.collection("Classes").document(c).get();
final data =
ClassData.fromUserMap(classsnapshot.data, classsnapshot.documentID);
if (data != null) {
classList.add(data);
// print(data.classdescription);
}
}
cs = classList;
}
UserData({this.firstName, this.rating, this.classes});
}
Here is the error I get when I load this widget.
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following NoSuchMethodError was thrown building YourClasses(dirty, dependencies: [MediaQuery,
flutter: _InheritedProviderScope<UserDataNotifier>, _InheritedProviderScope<UserData>], state:
flutter: _YourClassesState#4bf6d):
flutter: The getter 'getTheUserClasses' was called on null.
flutter: Receiver: null
flutter: Tried calling: getTheUserClasses
flutter:
flutter: The relevant error-causing widget was:
flutter: YourClasses
flutter: file:///Users/devintripp/Desktop/flutter_apps.no_sync/discoverytutors/lib/Screens/LoggedIn/TutorsView/tutors.dart:148:65
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
flutter: #1 _YourClassesState.build (package:disc_t/Screens/LoggedIn/Classes/yourclasses.dart:66:38)
flutter: #2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
flutter: #3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
flutter: #4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
flutter: #5 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
flutter: #6 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5)
flutter: #7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4666:11)
flutter: #8 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
flutter: ... Normal element mounting (24 frames)
flutter: #32 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
flutter: #33 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5947:32)
flutter: ... Normal element mounting (119 frames)
flutter: #152 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
flutter: #153 Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
flutter: #154 RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5580:32)
flutter: #155 MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5957:17)
flutter: #156 Element.updateChild (package:flutter/src/widgets/framework.dart:3201:15)
flutter: #157 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
flutter: #158 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
flutter: #159 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
flutter: #160 StatefulElement.update (package:flutter/src/widgets/framework.dart:4707:5)
flutter: #161 Element.updateChild (package:flutter/src/widgets/framework.dart:3201:15)
flutter: #162 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
flutter: #163 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
flutter: #164 ProxyElement.update (package:flutter/src/widgets/framework.dart:4862:5)
flutter: #165 _InheritedNotifierElement.update (package:flutter/src/widgets/inherited_notifier.dart:181:11)
flutter: #166 Element.updateChild (package:flutter/src/widgets/framework.dart:3201:15)
flutter: #167 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5837:14)
flutter: #168 Element.updateChild (package:flutter/src/widgets/framework.dart:3201:15)
flutter: #169 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
flutter: #170 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
flutter: #171 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
flutter: #172 StatefulElement.update (package:flutter/src/widgets/framework.dart:4707:5)
flutter: #173 Element.updateChild (package:flutter/src/widgets/framework.dart:3201:15)
flutter: #174 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5837:14)
flutter: #175 Element.updateChild (package:flutter/src/widgets/framework.dart:3201:15)
flutter: #176 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5837:14)
flutter: #177 Element.updateChild (package:flutter/src/widgets/framework.dart:3201:15)
flutter: #178 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
flutter: #179 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
flutter: #180 StatelessElement.update (package:flutter/src/widgets/framework.dart:4583:5)
flutter: #181 Element.updateChild (package:flutter/src/widgets/framework.dart:3201:15)
flutter: #182 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4527:16)
flutter: #183 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
flutter: #184 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
flutter: #185 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2627:33)
flutter: #186 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:883:20)
flutter: #187 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:284:5)
flutter: #188 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1113:15)
flutter: #189 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1052:9)
flutter: #190 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:968:5)
flutter: #194 _invoke (dart:ui/hooks.dart:261:10)
flutter: #195 _drawFrame (dart:ui/hooks.dart:219:3)
flutter: (elided 3 frames from dart:async)
Here is the screen that is loaded at first.
then when it duplicates it gets the same data 3 times. This is after i refresh this widget.
Instead of using a StreamBuilder, use a FutureBuilder.
Instead of creating your Future on every build, create the Future once and save it to a variable in your state, so it does not get called again and again, but only once, no matter how many times your build method is called.
Stream.fromFuture() does not cover your use case. It will not update if new elements are added or elements are deleted (since it just gets the elements from a Future).
In your case you might want to do something like the following:
Stream<List<YourModel>> getUserList() {
return Firestore.instance.collection('Classes')
.snapshots()
.map((snapShot) => snapShot.documents
.map((document) => Yourmodel.fromDocument(document.data)
.toList());
}
Furthermore, in order to avoid the error you see in the console, you need to check whether the document has data (e.g. if (document.hasData())) and return the widget to be displayed if no data is available yet.

Unhandled Exception: NoSuchMethodError: The method 'split' was called on null

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

'firebase/main.dart': Failed assertion

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

Resources