Bad state no element in Flutter Using FutureBuilder and Provider - flutter

Using Provider and FutureBuilder, I just deleted data from database, it got removed at the same time, it shows a red screen with bad state no element. There is no problem to add data, do not show this problem.
Code is given below
stacktrace
ter (12519): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (12519): The following StateError was thrown building ViewNoteScreen(dirty, dependencies:
I/flutter (12519): [_ModalScopeStatus], state: _ViewNoteScreenState#f589b):
I/flutter (12519): Bad state: No element
I/flutter (12519):
I/flutter (12519): The relevant error-causing widget was:
I/flutter (12519): ViewNoteScreen file:///C:/Users/Admin/Desktop/daily%2010/provider_note/lib/main.dart:21:46
I/flutter (12519):
I/flutter (12519): When the exception was thrown, this was the stack:
I/flutter (12519): #0 ListMixin.firstWhere (dart:collection/list.dart:148:5)
I/flutter (12519): #1 Providers.findById (package:provider_note/helper/provider.dart:14:19)
I/flutter (12519): #2 _ViewNoteScreenState.build (package:provider_note/screens/view_note.dart:21:35)
I/flutter (12519): #3 StatefulElement.build (package:flutter/src/widgets/framework.dart:4663:28)
I/flutter (12519): #4 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
I/flutter (12519): #5 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
I/flutter (12519): #6 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
I/flutter (12519): #7 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2667:33)
I/flutter (12519): #8 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:866:20)
I/flutter (12519): #9 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:286:5)
I/flutter (12519): #10 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15)
I/flutter (12519): #11 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1056:9)
I/flutter (12519): #12 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:972:5)
I/flutter (12519): #16 _invoke (dart:ui/hooks.dart:253:10)
I/flutter (12519): #17 _drawFrame (dart:ui/hooks.dart:211:3)
I/flutter (12519): (elided 3 frames from dart:async)
I/flutter (12519):
I/flutter (12519): ══════════════════════════════════════════════

BadStateException occurred when list don't contain the item and still someone searching for that
Example:
If orElse not defined in the code and the wrong item gets search which doesn't exist in the list then it shows BadStateException
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element.contains('green'));
print(newList);
}
Output:
Uncaught Error: Bad state: No element
Solution: Add orElse
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element.contains(''),
orElse: () => 'No matching color found');
print(newList);
}
Output:
No matching color found

I think the easiest way for you is change your home to statefull widget and change this part of your code.
Navigator.pushNamed(
context, ViewNoteScreen.routeName,
arguments: notes.items[i].id).whenComplete(() {
setState(() {});
});

Related

Flutter, DropDownButton Either zero or 2 or more [DropdownMenuItem]s were detected with the same value

I'm new in flutter, and I was trying to make a Dropdownbuttom item, where users can select one item from the list (which I take from FirebaseFirestore), and if the user takes that item, and save it using the button, that item won't be available for others users.
This is the method for the onPress() function from my save's button.
Future saveData(String uid, String enrollment) async {
// Limpiar la matricula donde aparezca el usuario.
final querySnapshot =
await FirebaseFirestore.instance.collection('Matriculas').get();
final enrollmentOld = querySnapshot.docs.firstWhere(
(doc) => doc['infoCoche']['idUser'] == uid,
orElse: () => null,
);
if (enrollmentOld != null) {
try {
FirebaseFirestore.instance
.collection('Matriculas')
.doc(enrollmentOld.id)
.update({
'infoCoche': {'idUser': uid, 'enUso': false}
});
} catch (e) {
print(e.toString());
}
}
//Update en la nueva matricula con el nuevo usuario
try {
FirebaseFirestore.instance
.collection('Matriculas')
.doc(enrollment)
.update({
'infoCoche': {'idUser': uid, 'enUso': true}
});
} catch (e) {
print(e.toString());
}
}
First I search if the user has already an enrollment selected, so if he wants to change to another one I can release the old one. If so, I put the bool enUso to false. Do the same for the item that he's selecting but true. If don't, I just ignore that part and change the new enrollment's attribute to true.
This is the DropDownButton.
var _currentItemSelected;
Widget _formSelectEnrollment() {
return StreamBuilder(
stream: FirebaseFirestore.instance.collection('Matriculas').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
List<DocumentSnapshot> docs = snapshot.data.docs;
List<String> listEnrollment = List();
for (DocumentSnapshot ids in docs) {
if (!ids['infoCoche']['enUso']) {
listEnrollment.add(ids.id);
}
}
return Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Seleccionar matricula',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
),
SizedBox(
height: 10,
),
DropdownButtonFormField<String>(
items: listEnrollment.map((String dropDownStringItem) {
return DropdownMenuItem<String>(
value: dropDownStringItem,
child: Text(dropDownStringItem),
);
}).toList(),
validator: (value) => value == null
? 'Es necesario seleccionar una matricula'
: null,
onChanged: (String newValueSelected) {
setState(() {
_currentItemSelected = newValueSelected;
});
},
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xfff3f3f4),
filled: true),
)
],
),
);
},
);
}
As you can see I'm using StreamBuilder(), so I get a list with all enrollments which are not in use. Also due to it's a streambuilder, if I change something in FireStore it will change in real time.
But, for some reason, which I'm not concern about it, every time I try to select a new enrollment, and save it, it returns the next error.
Performing hot reload...
Reloaded 4 of 838 libraries in 282ms.
I/flutter (17066): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (17066): The following assertion was thrown building Builder(dirty, dependencies: [_FocusMarker]):
I/flutter (17066): There should be exactly one item with [DropdownButton]'s value: 5816KNK.
I/flutter (17066): Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
I/flutter (17066): 'package:flutter/src/material/dropdown.dart':
I/flutter (17066): Failed assertion: line 834 pos 15: 'items == null || items.isEmpty || value == null ||
I/flutter (17066): items.where((DropdownMenuItem<T> item) {
I/flutter (17066): return item.value == value;
I/flutter (17066): }).length == 1'
I/flutter (17066):
I/flutter (17066): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter (17066): more information in this error message to help you determine and fix the underlying cause.
I/flutter (17066): In either case, please report this assertion by filing a bug on GitHub:
I/flutter (17066): https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter (17066):
I/flutter (17066): The relevant error-causing widget was:
I/flutter (17066): DropdownButtonFormField<String>
I/flutter (17066): file:///C:/Users/Sharki/Documents/4.%20Proyecto%20flutter/Pruebas%20Flutter/Asereje/lib/paginas/accountSettings.dart:55:15
I/flutter (17066):
I/flutter (17066): When the exception was thrown, this was the stack:
I/flutter (17066): #2 new DropdownButton (package:flutter/src/material/dropdown.dart:834:15)
I/flutter (17066): #3 new DropdownButtonFormField.<anonymous closure>.<anonymous closure> (package:flutter/src/material/dropdown.dart:1525:27)
I/flutter (17066): #4 Builder.build (package:flutter/src/widgets/basic.dart:7183:48)
I/flutter (17066): #5 StatelessElement.build (package:flutter/src/widgets/framework.dart:4701:28)
I/flutter (17066): #6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4627:15)
I/flutter (17066): #7 Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
I/flutter (17066): #8 StatelessElement.update (package:flutter/src/widgets/framework.dart:4708:5)
I/flutter (17066): #9 Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15)
I/flutter (17066): #10 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6125:14)
I/flutter (17066): #11 Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15)
I/flutter (17066): #12 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
I/flutter (17066): #13 Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
I/flutter (17066): #14 ProxyElement.update (package:flutter/src/widgets/framework.dart:4987:5)
I/flutter (17066): #15 _InheritedNotifierElement.update (package:flutter/src/widgets/inherited_notifier.dart:183:11)
I/flutter (17066): #16 Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15)
I/flutter (17066): #17 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
I/flutter (17066): #18 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4800:11)
I/flutter (17066): #19 Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
I/flutter (17066): #20 StatefulElement.update (package:flutter/src/widgets/framework.dart:4832:5)
I/flutter (17066): #21 Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15)
I/flutter (17066): #22 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
I/flutter (17066): #23 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4800:11)
I/flutter (17066): #24 Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
I/flutter (17066): #25 StatefulElement.update (package:flutter/src/widgets/framework.dart:4832:5)
I/flutter (17066): #26 Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15)
I/flutter (17066): #27 RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5647:32)
I/flutter (17066): #28 MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6246:17)
I/flutter (17066): #29 Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15)
I/flutter (17066): #30 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6125:14)
I/flutter (17066): #31 Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15)
I/flutter (17066): #32 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
I/flutter (17066): #33 Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
I/flutter (17066): #34 StatelessElement.update (package:flutter/src/widgets/framework.dart:4708:5)
I/flutter (17066): #35 Element.updateChild (package:flutter/src/widgets/framework.dart:3314:15)
I/flutter (17066): #36 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4652:16)
I/flutter (17066): #37 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4800:11)
I/flutter (17066): #38 Element.rebuild (package:flutter/src/widgets/framework.dart:4343:5)
I/flutter (17066): #39 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2730:33)
I/flutter (17066): #40 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:913:20)
I/flutter (17066): #41 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:302:5)
I/flutter (17066): #42 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15)
I/flutter (17066): #43 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1055:9)
I/flutter (17066): #44 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:971:5)
I/flutter (17066): #48 _invoke (dart:ui/hooks.dart:251:10)
I/flutter (17066): #49 _drawFrame (dart:ui/hooks.dart:209:3)
I/flutter (17066): (elided 5 frames from class _AssertionError and dart:async)
I/flutter (17066):
I/flutter (17066): ════════════════════════════════════════════════════════════════════════════════════════════════════
As I said, I'm really new in flutter, also I'm sorry for my English.
The problem is in DropDown item builder
here
listEnrollment.map((String dropDownStringItem) {
return DropdownMenuItem<String>(
value: dropDownStringItem,
child: Text(dropDownStringItem),
);
you must have different value of dropDownStringItem here
as according to this error
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
so check the values in listEnrollement you might solve this after that
Also check listEnrollement isn't empty at the time of build

Flutter Error : MediaQuery.of() called with a context that does not contain a MediaQuery

I have just started learning app development via Flutter. I ran into a tutorial to build a simple app.
My task is to add appbar and I did this:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Hello '),
),
),
));
}
I am expecting a simple app bar with the title "Hello ".
I get this error in console :
-I/flutter (17741): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (17741): The following assertion was thrown building MyApp:
I/flutter (17741): MediaQuery.of() called with a context that does not contain a MediaQuery.
I/flutter (17741): No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
I/flutter (17741): This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce
I/flutter (17741): a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
I/flutter (17741): The context used was:
I/flutter (17741): Scaffold
I/flutter (17741):
I/flutter (17741): The relevant error-causing widget was:
I/flutter (17741): MyApp file:///E:/Flutter/i_am_rich/lib/main.dart:3:23
I/flutter (17741):
I/flutter (17741): When the exception was thrown, this was the stack:
I/flutter (17741): #0 MediaQuery.of (package:flutter/src/widgets/media_query.dart:798:5)
I/flutter (17741): #1 ScaffoldState.didChangeDependencies (package:flutter/src/material/scaffold.dart:1993:50)
I/flutter (17741): #2 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4376:12)
I/flutter (17741): #3 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
I/flutter (17741): #4 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
I/flutter (17741): #5 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
I/flutter (17741): #6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
Reloaded 1 of 478 libraries in 437ms.
I/flutter (17741): #7 Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
I/flutter (17741): #8 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2432:33)
I/flutter (17741): #9 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:773:20)
I/flutter (17741): #10 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:283:5)
I/flutter (17741): #11 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1102:15)
I/flutter (17741): #12 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1041:9)
I/flutter (17741): #13 SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:850:7)
I/flutter (17741): #15 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:384:19)
I/flutter (17741): #16 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:418:5)
I/flutter (17741): #17 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)
I/flutter (17741): (elided one frame from package dart:async-patch)
I/flutter (17741):
I/flutter (17741):
════════════════════════════════════════════════════════════════════════════════════════════════════
It would be great if you could provide me some insights into this.
Issue was solved on suggestion of #VirenVVarasadiya by running:
flutter clean
flutter run

SchedulerBinding vs WidgetsBinding

Actually I am working on Login page with Bloc. So when I press submit button, it does business logic on bloc then trying to navigate to home page based on the result. I tried this
Widget submitButton() {
return StreamBuilder(
stream: bloc.submitStream,
builder: (context, snapshot) {
if (snapshot.data == "Success") {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RegisterPage(),
),
);
}
return RaisedButton(
child: Text("Submit"),
onPressed: () {
bloc.submitSink.add(null);
},
);
},
);
}
But I got error like this The widget which was currently being built when the offending call was made....
Later then I found two solution:
1. Using SchedulerBinding,
2. Using WidgetsBinding. So what is the difference between SchedulerBinding and WidgetsBinding. Which one do I have to use?
Full Error Log:
I/flutter (17893): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (17893): The following assertion was thrown building LayoutBuilder:
I/flutter (17893): setState() or markNeedsBuild() called during build.
I/flutter (17893): This Overlay widget cannot be marked as needing to build because the framework is already in the
I/flutter (17893): process of building widgets. A widget can be marked as needing to be built during the build phase
I/flutter (17893): only if one of its ancestors is currently building. This exception is allowed because the framework
I/flutter (17893): builds parent widgets before children, which means a dirty descendant will always be built.
I/flutter (17893): Otherwise, the framework might not visit this widget during this build phase.
I/flutter (17893): The widget on which setState() or markNeedsBuild() was called was:
I/flutter (17893): Overlay-[LabeledGlobalKey<OverlayState>#70089](state: OverlayState#3bf13(entries:
I/flutter (17893): [OverlayEntry#9280a(opaque: false; maintainState: false), OverlayEntry#1af87(opaque: false;
I/flutter (17893): maintainState: true), OverlayEntry#9fb49(opaque: false; maintainState: false),
I/flutter (17893): OverlayEntry#87589(opaque: false; maintainState: true)]))
I/flutter (17893): The widget which was currently being built when the offending call was made was:
I/flutter (17893): LayoutBuilder(renderObject: _RenderLayoutBuilder#d3baf relayoutBoundary=up1 NEEDS-LAYOUT
I/flutter (17893): NEEDS-PAINT)
I/flutter (17893):
I/flutter (17893): When the exception was thrown, this was the stack:
I/flutter (17893): #0 Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:3497:11)
I/flutter (17893): #1 Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:3523:6)
I/flutter (17893): #2 State.setState (package:flutter/src/widgets/framework.dart:1138:14)
I/flutter (17893): #3 OverlayState.insertAll (package:flutter/src/widgets/overlay.dart:301:5)
I/flutter (17893): #4 OverlayRoute.install (package:flutter/src/widgets/routes.dart:43:24)
I/flutter (17893): #5 TransitionRoute.install (package:flutter/src/widgets/routes.dart:184:11)
I/flutter (17893): #6 ModalRoute.install (package:flutter/src/widgets/routes.dart:899:11)
I/flutter (17893): #7 NavigatorState.push (package:flutter/src/widgets/navigator.dart:1672:11)
I/flutter (17893): #8 Navigator.push (package:flutter/src/widgets/navigator.dart:1011:34)
I/flutter (17893): #9 _SetPinPageState.submitButton (package:technicalreport/screens/set_pin_page.dart:94:15)
I/flutter (17893): #10 _SetPinPageState.build.<anonymous closure>.<anonymous closure> (package:technicalreport/screens/set_pin_page.dart:52:29)
I/flutter (17893): #11 OrientationBuilder._buildWithConstraints (package:flutter/src/widgets/orientation_builder.dart:48:12)
I/flutter (17893): #12 _LayoutBuilderElement._layout.<anonymous closure> (package:flutter/src/widgets/layout_builder.dart:111:26)
I/flutter (17893): #13 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2253:19)
I/flutter (17893): #14 _LayoutBuilderElement._layout (package:flutter/src/widgets/layout_builder.dart:107:11)
I/flutter (17893): #15 RenderObject.invokeLayoutCallback.<anonymous closure> (package:flutter/src/rendering/object.dart:1728:58)
I/flutter (17893): #16 PipelineOwner._enableMutationsToDirtySubtrees (package:flutter/src/rendering/object.dart:797:15)
I/flutter (17893): #17 RenderObject.invokeLayoutCallback (package:flutter/src/rendering/object.dart:1728:13)
I/flutter (17893): #18 _RenderLayoutBuilder.performLayout (package:flutter/src/widgets/layout_builder.dart:205:5)
I/flutter (17893): #19 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #20 MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:142:11)
I/flutter (17893): #21 _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:350:7)
I/flutter (17893): #22 MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:212:7)
I/flutter (17893): #23 RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:356:14)
I/flutter (17893): #24 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #25 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #26 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #27 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #28 _RenderCustomClip.performLayout (package:flutter/src/rendering/proxy_box.dart:1206:11)
I/flutter (17893): #29 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #30 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #31 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #32 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #33 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #34 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #35 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #36 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #37 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #38 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #39 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #40 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #41 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #42 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #43 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #44 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #45 RenderOffstage.performLayout (package:flutter/src/rendering/proxy_box.dart:3032:13)
I/flutter (17893): #46 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #47 RenderStack.performLayout (package:flutter/src/rendering/stack.dart:510:15)
I/flutter (17893): #48 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #49 __RenderTheatre&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #50 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #51 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #52 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #53 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #54 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #55 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #56 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #57 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
I/flutter (17893): #58 RenderObject.layout (package:flutter/src/rendering/object.dart:1632:7)
I/flutter (17893): #59 RenderView.performLayout (package:flutter/src/rendering/view.dart:151:13)
I/flutter (17893): #60 RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1507:7)
I/flutter (17893): #61 PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:766:18)
I/flutter (17893): #62 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:329:19)
I/flutter (17893): #63 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:701:13)
I/flutter (17893): #64 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:268:5)
I/flutter (17893): #65 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:988:15)
I/flutter (17893): #66 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:928:9)
I/flutter (17893): #67 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:749:7)
I/flutter (17893): #76 _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
I/flutter (17893): #77 _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
I/flutter (17893): #78 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
I/flutter (17893): (elided 8 frames from package dart:async)
I/flutter (17893): ════════════════════════════════════════════════════════════════════════════════════════════════════
D/ (17893): HostConnection::get() New Host Connection established 0xa0ba6b40, tid 17931
D/EGL_emulation(17893): eglMakeCurrent: 0xa3508c40: ver 2 0 (tinfo 0x9084ab40)
There are three callbacks available in flutter which rendering flutter widgets.
Transient callbacks: triggered by the system’s [Window.onBeginFrame] callback, for synchronizing the application’s behavior to the system’s display. For example, [Ticker]s and [AnimationController]s trigger from these.
Persistent callbacks: triggered by the system’s [Window.onDrawFrame] callback, for updating the system’s display after transient callbacks have executed. For example, the rendering layer uses this to drive its rendering pipeline.
Post-frame callbacks: which are run after persistent callbacks, just before returning from the [Window.onDrawFrame] callback. * Non-rendering tasks, to be run between frames. These are given a priority and are executed in priority order according to a schedulingStrategy.
All above callbacks run sequentially, but for us, the last callback would work i.e Post-frame callbacks
Widgets Binding: The glue between the widgets layer and the Flutter engine. which comes with WidgetsBindingObserver mixin which has many callbacks but one which required to use is didChangeAppLifecycleState that returns AppLifecycleState.
Scheduler Binding: This is also similar to WidgetBinding but it does not provide any life cycle callbacks.
The below binding example would be called exactly the ones, means print statement like WidgetsBinding & SchedulerBinding will be printed only once as we called it initState(), but it will be called when build method finished it’s rendering.
void initState() {
super.initState();
print("initState");
WidgetsBinding.instance.addPostFrameCallback((_) {
print("WidgetsBinding");
});
SchedulerBinding.instance.addPostFrameCallback((_) {
print("SchedulerBinding");
});
}
Both solutions do the same.
WidgetsBinding inherits this Method from SchedulerBinding
https://api.flutter.dev/flutter/widgets/WidgetsBinding-mixin.html
It registers a callback that will be called after the frame is build.
See in the docs:
https://api.flutter.dev/flutter/scheduler/SchedulerBinding/addPostFrameCallback.html

Flutter: navigate to another screen from inside of StreamBuilder builder callback

I have a splash screen and a StreamBuilder that emits a state that contains information about authentication status. When the authentication status is known, I want to navigate either to sign in page or home page. But when I write something like Navigator.of(context).pushReplacement(...) I get
I/flutter ( 2058): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 2058): The following assertion was thrown building StreamBuilder(dirty, state:
I/flutter ( 2058): _StreamBuilderBaseState>#f4346):
I/flutter ( 2058): setState() or markNeedsBuild() called during build.
I/flutter ( 2058): This Overlay widget cannot be marked as needing to build because the framework is already in the
I/flutter ( 2058): process of building widgets. A widget can be marked as needing to be built during the build phase
I/flutter ( 2058): only if one of its ancestors is currently building. This exception is allowed because the framework
I/flutter ( 2058): builds parent widgets before children, which means a dirty descendant will always be built.
I/flutter ( 2058): Otherwise, the framework might not visit this widget during this build phase.
I/flutter ( 2058): The widget on which setState() or markNeedsBuild() was called was:
I/flutter ( 2058): Overlay-[LabeledGlobalKey#e0460](state: OverlayState#ab1a5(entries:
I/flutter ( 2058): [OverlayEntry#4e962(opaque: false; maintainState: false), OverlayEntry#7656a(opaque: false;
I/flutter ( 2058): maintainState: true), OverlayEntry#1f86e(opaque: false; maintainState: false),
I/flutter ( 2058): OverlayEntry#05a15(opaque: false; maintainState: true)]))
I/flutter ( 2058): The widget which was currently being built when the offending call was made was:
I/flutter ( 2058): StreamBuilder(dirty, state: _StreamBuilderBaseState>#f4346)
I/flutter ( 2058):
I/flutter ( 2058): When the exception was thrown, this was the stack:
I/flutter ( 2058): #0 Element.markNeedsBuild. (package:flutter/src/widgets/framework.dart:3503:11)
I/flutter ( 2058): #1 Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:3529:6)
I/flutter ( 2058): #2 State.setState (package:flutter/src/widgets/framework.dart:1133:14)
I/flutter ( 2058): #3 OverlayState.insertAll (package:flutter/src/widgets/overlay.dart:346:5)
I/flutter ( 2058): #4 OverlayRoute.install (package:flutter/src/widgets/routes.dart:43:24)
I/flutter ( 2058): #5 TransitionRoute.install (package:flutter/src/widgets/routes.dart:180:11)
I/flutter ( 2058): #6 ModalRoute.install (package:flutter/src/widgets/routes.dart:895:11)
I/flutter ( 2058): #7 NavigatorState.pushReplacement (package:flutter/src/widgets/navigator.dart:1799:14)
I/flutter ( 2058): #8 _replace (package:map_chat/application/navigation.dart:75:27)
I/flutter ( 2058): #9 _SignInPage.replace (package:map_chat/application/navigation.dart:67:5)
I/flutter ( 2058): #10 Roadmap.replace (package:map_chat/application/navigation.dart:25:18)
I/flutter ( 2058): #11 _SplashPageState._buildPageBasedOnAuthenticationState (package:map_chat/feature/splash.dart:52:19)
I/flutter ( 2058): #12 _SplashPageState._buildSplashScreen (package:map_chat/feature/splash.dart:40:11)
I/flutter ( 2058): #13 _SplashPageState._buildPage. (package:map_chat/feature/splash.dart:27:18)
I/flutter ( 2058): #14 StreamBuilder.build (package:flutter/src/widgets/async.dart:425:74)
I/flutter ( 2058): #15 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
I/flutter ( 2058): #16 StatefulElement.build (package:flutter/src/widgets/framework.dart:3825:27)
I/flutter ( 2058): #17 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3739:15)
I/flutter ( 2058): #18 Element.rebuild (package:flutter/src/widgets/framework.dart:3565:5)
I/flutter ( 2058): #19 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2278:33)
I/flutter ( 2058): #20 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
I/flutter ( 2058): #21 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:286:5)
I/flutter ( 2058): #22 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1012:15)
I/flutter ( 2058): #23 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:952:9)
I/flutter ( 2058): #24 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.scheduleWarmUpFrame. (package:flutter/src/scheduler/binding.dart:773:7)
I/flutter ( 2058): #33 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:382:19)
I/flutter ( 2058): #34 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:416:5)
I/flutter ( 2058): #35 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)
I/flutter ( 2058): (elided 8 frames from package dart:async and package dart:async-patch)
The only workaround I found is to schedule the navigation to the end of event queue using Future(...).then(navigate) but that's sick. Is here an adequate solution for this?
You can listen your stream outside of build method and redirect to another view from there.
---- EDITED ----
This is an example of how you can do that:
#override
void initState() {
super.initState();
Future.delayed(Duration.zero, _verify);
}
void _verify() {
final _myBloc = BlocProvider.getBloc<MyBloc>();
_myBloc.myStream.listen((data) {
// Redirect to another view, given your condition
if (data) {
Navigator.of(context).pushNamed("my-new-route");
}
});
}
Just remember to save the StreamSubscription object returned from listen method, so you can cancel the subscription on dispose().
I still not happy with my solution, but I use a
if(snapshot.hasdata && snapshot.data.navigate) {
Future.microtask(() => Navigator.of(context).push... );
}

Handle errors network image loading

My app is displaying lots of images, and some urls may not be valid.
This is the code i use to display the image:
(I use the cached_network_image plugin)
CachedNetworkImage(
imageUrl: images.first,
fit: BoxFit.cover,
placeholder: (context, url) => Center(
child: CircularProgressIndicator(),
),
errorWidget: (context, url, error) => Center(
child: const Icon(Icons.error)
)
)
Basically, there is the error that is thrown:
E/flutter (28425): [ERROR:flutter/lib/ui/painting/codec.cc(97)] Failed decoding image. Data is either invalid, or it is encoded using an unsupported format.
I/flutter (28425): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════
I/flutter (28425): The following _Exception was thrown resolving an image codec:
I/flutter (28425): Exception: operation failed
I/flutter (28425):
I/flutter (28425): When the exception was thrown, this was the stack:
I/flutter (28425): #0 FileImage._loadAsync (package:flutter/src/painting/image_provider.dart:564:12)
I/flutter (28425): <asynchronous suspension>
I/flutter (28425): #1 FileImage.load (package:flutter/src/painting/image_provider.dart:549:14)
I/flutter (28425): #2 ImageProvider.resolve.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:285:105)
I/flutter (28425): #3 ImageCache.putIfAbsent (package:flutter/src/painting/image_cache.dart:157:22)
I/flutter (28425): #4 ImageProvider.resolve.<anonymous closure> (package:flutter/src/painting/image_provider.dart:285:82)
I/flutter (28425): #5 SynchronousFuture.then (package:flutter/src/foundation/synchronous_future.dart:38:29)
I/flutter (28425): #6 ImageProvider.resolve (package:flutter/src/painting/image_provider.dart:283:30)
I/flutter (28425): #7 _ImageState._resolveImage (package:flutter/src/widgets/image.dart:631:20)
I/flutter (28425): #8 _ImageState.didChangeDependencies (package:flutter/src/widgets/image.dart:606:5)
I/flutter (28425): #9 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3862:12)
I/flutter (28425): #10 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3711:5)
I/flutter (28425): #11 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
I/flutter (28425): #12 Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
I/flutter (28425): #13 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:4883:14)
I/flutter (28425): #14 Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
I/flutter (28425): #15 RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:4601:32)
I/flutter (28425): #16 MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:4992:17)
I/flutter (28425): #17 Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
I/flutter (28425): #18 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
I/flutter (28425): #19 Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
I/flutter (28425): #20 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2273:33)
I/flutter (28425): #21 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
I/flutter (28425): #22 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:268:5)
I/flutter (28425): #23 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:988:15)
I/flutter (28425): #24 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:928:9)
I/flutter (28425): #25 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:840:5)
I/flutter (28425): #29 _invoke (dart:ui/hooks.dart:209:10)
I/flutter (28425): #30 _drawFrame (dart:ui/hooks.dart:168:3)
I/flutter (28425): (elided 3 frames from package dart:async)
I/flutter (28425):
I/flutter (28425): Path:
I/flutter (28425): /data/user/0/xx.xxxx.xxxxxxxxxxx/cache/libCachedImageData/31c76660-5970-11e9-b769-3943ba44d1cb.html;
I/flutter (28425): charset=UTF-8
I/flutter (28425): ════════════════════════════════════════════════════════════════════════════════════════════════════
Notice that this url give some html... so that's normal
As I do not found any way to handle that error, i tried to use NetworkImageWithRetry from flutter_image package using:
FadeInImage(
placeholder: MemoryImage(kTransparentImage),
image: NetworkImageWithRetry(
imageUrl
),
fit: BoxFit.cover,
fadeInDuration: Duration(milliseconds: 150)
)
There is example of error that is thrown this time:
[ERROR:flutter/lib/ui/painting/codec.cc(97)] Failed decoding image. Data is either invalid, or it is encoded using an unsupported format.
I/flutter (31334): ══╡ EXCEPTION CAUGHT BY PACKAGE:FLUTTER_IMAGE ╞═════════════════════════════════════════════════════
I/flutter (31334): The following FetchFailure was thrown NetworkImageWithRetry failed to load
I/flutter (31334): xxxxxxxxxxxxxxxx :
I/flutter (31334): FetchFailure(
I/flutter (31334): attemptCount: 1
I/flutter (31334): httpStatusCode: null
I/flutter (31334): totalDuration: 0:00:05.969844
I/flutter (31334): originalException: Exception: operation failed
I/flutter (31334): )
I/flutter (31334): ════════════════════════════════════════════════════════════════════════════════════════════════════
This url send html...
The problem is that in release mode, I force close the app in case of any error, so i need to handle them
how can I just handle this types of error ?