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.
Related
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:
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.
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 am trying to connect my Flutter app with Firebase but it shows lots of error I don't know what is wrong. In this basically I am pressing the flat button to connect using firbase_auth and create a user.
I am using AndroidX and installed packages and also tried flutter clean, but nothing works, I followed all instructions in firebase to register my app for android and also multiDexEnabled to true in app level build.gradle
My code:-
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class ConnectionPage extends StatelessWidget {
final _auth = FirebaseAuth.instance;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white12,
title: Text("Connection Page"),
),
backgroundColor: Colors.black,
body: Center(
child: Container(
height: 400,
child: FlatButton(
child: Text("Button"),
onPressed: () async {
final userInfo = await _auth.createUserWithEmailAndPassword(email: "vishnu#email.com", password: "1234");
print(userInfo.user);
}
),
),
),
);
}
}
and this is pubspec.yaml
name: stockexchange
description: A new Flutter application.
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
english_words: ^3.1.0
google_fonts: ^0.3.10
charts_flutter: ^0.9.0
firebase_core: ^0.4.4+3
firebase_auth: ^0.16.0
cloud_firestore: ^0.13.5
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- images/
fonts:
- family: CustomIcon
fonts:
- asset: fonts/CustomIcon.ttf
and this the error I am having after running and typing
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): Failed to handle method call
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist.
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common##19.3.0:218)
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at io.flutter.plugins.firebaseauth.FirebaseAuthPlugin.getAuth(FirebaseAuthPlugin.java:129)
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at io.flutter.plugins.firebaseauth.FirebaseAuthPlugin.onMethodCall(FirebaseAuthPlugin.java:143)
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:231)
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:93)
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:642)
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at android.os.MessageQueue.next(MessageQueue.java:336)
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at android.os.Looper.loop(Looper.java:174)
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at android.app.ActivityThread.main(ActivityThread.java:7356)
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/MethodChannel#plugins.flutter.io/firebase_auth( 6904): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
E/flutter ( 6904): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, FirebaseApp with name [DEFAULT] doesn't exist. , null)
E/flutter ( 6904): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter ( 6904): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:321:33)
E/flutter ( 6904): <asynchronous suspension>
E/flutter ( 6904): #2 MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:349:48)
E/flutter ( 6904): #3 MethodChannelFirebaseAuth.createUserWithEmailAndPassword (package:firebase_auth_platform_interface/src/method_channel_firebase_auth.dart:64:23)
E/flutter ( 6904): #4 FirebaseAuth.createUserWithEmailAndPassword (package:firebase_auth/src/firebase_auth.dart:64:10)
E/flutter ( 6904): #5 _AsyncAwaitCompleter.start (dart:async-patch/async_patch.dart:45:6)
E/flutter ( 6904): #6 FirebaseAuth.createUserWithEmailAndPassword (package:firebase_auth/src/firebase_auth.dart:57:52)
E/flutter ( 6904): #7 ConnectionPage.build.<anonymous closure> (package:stockexchange/pages/connection_spec_page.dart:42:46)
E/flutter ( 6904): #8 _AsyncAwaitCompleter.start (dart:async-patch/async_patch.dart:45:6)
E/flutter ( 6904): #9 ConnectionPage.build.<anonymous closure> (package:stockexchange/pages/connection_spec_page.dart:38:30)
E/flutter ( 6904): #10 InputBoardState.build.<anonymous closure> (package:stockexchange/components/input_board.dart:110:24)
E/flutter ( 6904): #11 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter ( 6904): #12 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter ( 6904): #13 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter ( 6904): #14 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter ( 6904): #15 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter ( 6904): #16 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:199:7)
E/flutter ( 6904): #17 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:467:9)
E/flutter ( 6904): #18 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter ( 6904): #19 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:117:9)
E/flutter ( 6904): #20 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter ( 6904): #21 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:115:18)
E/flutter ( 6904): #22 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:7)
E/flutter ( 6904): #23 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter ( 6904): #24 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter ( 6904): #25 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter ( 6904): #26 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter ( 6904): #27 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter ( 6904): #28 _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter ( 6904): #29 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter ( 6904): #30 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter ( 6904): #31 _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter ( 6904): #32 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
E/flutter ( 6904):
This could happen if you skip some of the necessary steps to hook up your Flutter app to Firebase. You not only have to place google-service.json file into your android/app directory, but you also have to edit two build.gradle files.
I would recommend you make sure to follow each and every step in the official documentation below:
https://firebase.google.com/docs/flutter/setup
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');
});
}
}