Flutter: RenderBox was not laid out - dart

I'm trying to create a ListView but when I import the list_form.dart class i get this error. Maybe I made some mistakes with the layout because if I try to run it inside the main file I don't get this error.
This is the error:
I/flutter (12956): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter (12956): The following assertion was thrown during performResize():
I/flutter (12956): Vertical viewport was given unbounded height.
I/flutter (12956): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter (12956): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter (12956): typically happens when a scrollable widget is nested inside another scrollable widget.
I/flutter (12956): If this widget is always nested in a scrollable widget there is no need to use a viewport because
I/flutter (12956): there will always be enough vertical space for the children. In this case, consider using a Column
I/flutter (12956): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
I/flutter (12956): the height of the viewport to the sum of the heights of its children.
I/flutter (12956):
I/flutter (12956): When the exception was thrown, this was the stack:
I/flutter (12956): #0 RenderViewport.performResize.<anonymous closure> (package:flutter/src/rendering/viewport.dart:1133:15)
I/flutter (12956): #1 RenderViewport.performResize (package:flutter/src/rendering/viewport.dart:1186:6)
I/flutter (12956): #2 RenderObject.layout (package:flutter/src/rendering/object.dart:1616:9)
I/flutter (12956): #3 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #4 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #5 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #6 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #7 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #8 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #9 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #10 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #11 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #12 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #13 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #14 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #15 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #16 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #17 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #18 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #19 RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:738:15)
I/flutter (12956): #20 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #21 RenderFlex.performLayout (package:flutter/src/rendering/flex.dart:738:15)
I/flutter (12956): #22 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #23 RenderPositionedBox.performLayout (package:flutter/src/rendering/shifted_box.dart:381:13)
I/flutter (12956): #24 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #25 MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:141:11)
I/flutter (12956): #26 _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:339:7)
I/flutter (12956): #27 MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:211:7)
I/flutter (12956): #28 RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:355:14)
I/flutter (12956): #29 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #30 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #31 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #32 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #33 _RenderCustomClip.performLayout (package:flutter/src/rendering/proxy_box.dart:1192:11)
I/flutter (12956): #34 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #35 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #36 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #37 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #38 _RenderCustomClip.performLayout (package:flutter/src/rendering/proxy_box.dart:1192:11)
I/flutter (12956): #39 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #40 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #41 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #42 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #43 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #44 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #45 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #46 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #47 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #48 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #49 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #50 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #51 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #52 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #53 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #54 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #55 RenderOffstage.performLayout (package:flutter/src/rendering/proxy_box.dart:2884:13)
I/flutter (12956): #56 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #57 RenderStack.performLayout (package:flutter/src/rendering/stack.dart:520:15)
I/flutter (12956): #58 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #59 __RenderTheatre&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #60 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #61 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #62 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #63 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #64 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #65 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #66 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #67 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #68 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #69 _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:108:13)
I/flutter (12956): #70 RenderObject.layout (package:flutter/src/rendering/object.dart:1631:7)
I/flutter (12956): #71 RenderView.performLayout (package:flutter/src/rendering/view.dart:147:13)
I/flutter (12956): #72 RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1506:7)
I/flutter (12956): #73 PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:765:18)
I/flutter (12956): #74 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:270:19)
I/flutter (12956): #75 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:674:13)
I/flutter (12956): #76 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:208:5)
I/flutter (12956): #77 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter (12956): #78 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter (12956): #79 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:751:7)
I/flutter (12956): #81 _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
I/flutter (12956): #82 _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
I/flutter (12956): #83 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
I/flutter (12956): (elided one frame from package dart:async)
I/flutter (12956):
I/flutter (12956): The following RenderObject was being processed when the exception was fired:
I/flutter (12956): RenderViewport#925a8 NEEDS-LAYOUT NEEDS-PAINT
I/flutter (12956): creator: Viewport ← _ScrollableScope ← IgnorePointer-[GlobalKey#8e8f7] ← Semantics ← Listener ←
I/flutter (12956): _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#67ae5] ←
I/flutter (12956): _ScrollSemantics-[GlobalKey#17eb8] ← RepaintBoundary ← CustomPaint ← RepaintBoundary ←
I/flutter (12956): NotificationListener<ScrollNotification> ← ⋯
I/flutter (12956): parentData: <none> (can use size)
I/flutter (12956): constraints: BoxConstraints(unconstrained)
I/flutter (12956): size: MISSING
I/flutter (12956): axisDirection: down
I/flutter (12956): crossAxisDirection: right
I/flutter (12956): offset: ScrollPositionWithSingleContext#c4917(offset: 0.0, range: null..null, viewport: null,
I/flutter (12956): ScrollableState, AlwaysScrollableScrollPhysics -> ClampingScrollPhysics, IdleScrollActivity#2fecf,
I/flutter (12956): ScrollDirection.idle)
I/flutter (12956): anchor: 0.0
I/flutter (12956): This RenderObject had the following descendants (showing up to depth 5):
I/flutter (12956): RenderSliverPadding#74d62 NEEDS-LAYOUT NEEDS-PAINT
I/flutter (12956): RenderSliverList#5c56d NEEDS-LAYOUT NEEDS-PAINT
I/flutter (12956): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter (12956): Another exception was thrown: RenderBox was not laid out: RenderViewport#925a8 NEEDS-LAYOUT NEEDS-PAINT
I/flutter (12956): Another exception was thrown: RenderBox was not laid out: RenderViewport#925a8 NEEDS-PAINT
I/flutter (12956): Another exception was thrown: RenderBox was not laid out: RenderIgnorePointer#8bbda relayoutBoundary=up11 NEEDS-PAINT
I/flutter (12956): Another exception was thrown: RenderBox was not laid out: RenderSemanticsAnnotations#209b4 relayoutBoundary=up10 NEEDS-PAINT
I/flutter (12956): Another exception was thrown: RenderBox was not laid out: RenderPointerListener#a9641 relayoutBoundary=up9 NEEDS-PAINT
I/flutter (12956): Another exception was thrown: RenderBox was not laid out: RenderSemanticsGestureHandler#9f5b4 relayoutBoundary=up8 NEEDS-PAINT
I/flutter (12956): Another exception was thrown: RenderBox was not laid out: _RenderScrollSemantics#47944 relayoutBoundary=up7 NEEDS-PAINT
I/flutter (12956): Another exception was thrown: RenderBox was not laid out: RenderRepaintBoundary#e17a8 relayoutBoundary=up6 NEEDS-PAINT
I/flutter (12956): Another exception was thrown: RenderBox was not laid out: RenderCustomPaint#a2328 relayoutBoundary=up5 NEEDS-PAINT
I/flutter (12956): Another exception was thrown: RenderBox was not laid out: RenderRepaintBoundary#02607 relayoutBoundary=up4 NEEDS-PAINT
I/flutter (12956): Another exception was thrown: RenderBox was not laid out: RenderFlex#79164 relayoutBoundary=up3 NEEDS-PAINT
I/flutter (12956): Another exception was thrown: 'package:flutter/src/rendering/shifted_box.dart': Failed assertion: line 310 pos 12: 'child.hasSize': is not true.
I/flutter (12956): Another exception was thrown: NoSuchMethodError: The method '<=' was called on null.
This is the list_form.dart class:
import 'package:flutter/material.dart';
class ListForm extends StatefulWidget {
#override
ListFormState createState() => new ListFormState();
}
class ListFormState extends State<ListForm> {
List<String> products = ["Test1", "Test2", "Test3"];
#override
Widget build(BuildContext context) {
return new Container(
child: new Center(
child: new Column(
children: <Widget>[
new Row(
children: <Widget>[
new ListView.builder(
itemCount: products.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Text(products[index]);
}
),
new IconButton(
icon: Icon(Icons.remove_circle),
onPressed: () { },
)
],
mainAxisAlignment: MainAxisAlignment.spaceBetween,
),
new TextField(
decoration: new InputDecoration(
hintText: "Prodotto"
),
onSubmitted: (String str) {
setState(() {
products.add(str);
});
},
),
]
)
)
);
}
}
This is the app_base.dart class:
import 'package:flutter/material.dart';
import '../UI/list_form.dart';
class AppBase extends StatefulWidget {
#override
State createState() => new AppBaseState();
}
class AppBaseState extends State<AppBase> {
bool _pressed = true;
#override
Widget build(BuildContext context) {
return new Material(
color: Colors.greenAccent,
child: new Scaffold(
body:
new ListForm(),
appBar: AppBar(
centerTitle: true,
title: const Text('Skeeper'),
backgroundColor: Colors.green,
),
floatingActionButton: FloatingActionButton(
tooltip: 'Test',
child: new Icon(Icons.add),
backgroundColor: Colors.green,
onPressed: () {
setState(() {
_pressed = !_pressed;
});
},
),
)
);
}
}
Don't worry if there is some unused code, it's a work in progress and this error just stopped me continuing what I was doing.

The problem is that you are placing the ListView inside a Column/Row. The text in the exception gives a good explanation of the error.
To avoid the error you need to provide a size to the ListView inside.
I propose you this code that uses an Expanded to inform the horizontal size (maximum available) and the SizedBox (Could be a Container) for the height:
new Row(
children: <Widget>[
Expanded(
child: SizedBox(
height: 200.0,
child: new ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: products.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Text(products[index]);
},
),
),
),
new IconButton(
icon: Icon(Icons.remove_circle),
onPressed: () {},
),
],
mainAxisAlignment: MainAxisAlignment.spaceBetween,
)
,

You can add some code like this
ListView.builder{
shrinkWrap: true,
}

Reason for the error:
Column tries to expands in vertical axis, and so does the ListView, hence you need to constrain the height of ListView.
Solutions
Use either Expanded or Flexible if you want to allow ListView to take up entire left space in Column.
Column(
children: <Widget>[
Expanded(
child: ListView(...),
)
],
)
Use SizedBox if you want to restrict the size of ListView to a certain height.
Column(
children: <Widget>[
SizedBox(
height: 200, // constrain height
child: ListView(),
)
],
)
Use shrinkWrap, if your ListView isn't too big.
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // use it
)
],
)

use shrinkWrap: true,
With shrinkWrap: true, you can change this behavior so that the ListView only occupies the space it needs (it will still scroll when there more items).
If you set it to true, the list will wrap its content and be as big as it children allows it to be.
like this.
ListView.builder(
shrinkWrap: true,
itemBuilder: (context, index) {
.........
}
)

Placing your list view in a Flexible widget may also help,
Flexible( fit: FlexFit.tight, child: _buildYourListWidget(..),)

I used this code to fix the issue of displaying items in the horizontal list.
new Container(
height: 20,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: array.length,
itemBuilder: (context, index){
return array[index];
},
),
],
),
);

Wrap your ListView in an Expanded widget
Expanded(child:MyListView())

I had a similir problem, but in my case, I put a row in the leading of the ListView, and it was consuming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recommend to check if the problem is a larger widget than its container can have.
Expanded(child:MyListView())

I had a simmilar problem, but in my case I was put a row in the leading of the Listview, and it was consumming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recomend to check if the problem is a widget larger than its containner can have.

My app started crashing with the same error just completely out of the blue.
I really appreciate the other answers mentioned here on this page. But none worked for me. I was on Flutter 2.0.0 and upgrading to Flutter 2.2.2 fixed the issue without changing anything in my existing code.

Expanded widget will fix that problem, mainly that error occurs when you user multiples widgets with dynamic sizes in a column or a row

You can Always resolve this error in one of the following three ways:
Wrap your ListView with Expanded widget.
Wrap your ListView with SizedBox and give it a specific height.
You can add below your listView this line: shrinkWrap: true,

In the case where you are using a Column/Row ensure to specify the size they should occupy e.g.
SizedBox(
height: 100,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
CircularProgressIndicator(),
SizedBox(
width: 15,
),
Expanded(
child: Text("Data Laoding"),
)
],
),
),

See, wrap with expanded, no matter of anything.
Flexible widget also sometimes doesn't works.
Hope, this will be helpful.
Rendering,
Parent widget error,
Assertion are basic errors.
This will catch fears in a programmer.

I had similar issue, I was using an SvgPicture widget inside a SizedBox widget and instead of specifying the height property in the SizedBox I did it inside the SvgPicture widget.
If that is your case, then I recommend you specify the height of the SizedBox.

Wrap the list view inside a Container and specify the width.
Column(
children: [
Container(
width: MediaQuery.of(context).size.width,
child: ListView.builder(..)
This will solve the issue.

Related

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

UPDATE: Thanks to #Rjulcaa answer My map is now a List, however the List wasn't displayed on the UI. I turns that I needed to handle the future with a FutureBuilder, so in case anyone faces this problem remember to add a FutureBuilder to the body of your UI and on the builder return the widget you want to be displayed.
I'm making a todo list tutorial, I'm trying to add the feature of encoding on a JSON my todoList the save it on a sharedPreferences, and when I start the app retrieve it on the screen
This is my TODO class
class Todo {
Todo ({this.title,this.isDone = false});
String title;
bool isDone;
//Decode method to convert a Json String into a Dynamic object
Todo.fromJson(Map <String, dynamic> json)
: title = json ["title"],
isDone = json ["isDone"];
Map <String,dynamic> toJson() =>
{
"title" : title,
"isDone" : isDone
};
}
This is my screen
class _TodoListScreenState extends State<TodoListScreen> {
List<Todo> todos = [];
#override
void initState() {
super.initState();
_getTodoFromSharedPreferences();
}
//updates the state of the checkbox and reflects it on the UI
_toggleTodo(Todo todo, bool isChecked) {
setState(() {
todo.isDone = isChecked;
});
}
_addTodo() async {
final todo = await showDialog<Todo>(
context: context,
builder:(BuildContext context) { // <- Here you draw the Dialog
return NewTodoDialog();
},
);
if (todo != null) {
setState(() {
todos.add(todo);
_saveTodo(todos);
print(todos.length);
});
}
}
_saveTodo(List<Todo> todo) async{
final String newTodo = jsonEncode(todo);
setSharedPreferences(newTodo);
}
_getTodoFromSharedPreferences () async {
final prefs = await SharedPreferences.getInstance();
final savedTodo = prefs.getString("savedTodo");
if (savedTodo == null) {return null;} else {
Map MapofTodos = jsonDecode(savedTodo);
for (var i = 0; i < MapofTodos.length; ++i) {
var o = MapofTodos[i];
setState(() {
Todo todo = Todo.fromJson(o);
todos.add(todo);
});
}
}
}
setSharedPreferences (String newTodo ) async{
final prefs = await SharedPreferences.getInstance();
await prefs.setString("savedTodo", newTodo );
print(newTodo);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(backgroundColor:Colors.deepPurple[900] ,
title: Text('Todo List')),
body: TodoList(
todos: todos,
onTodoToggle: _toggleTodo,
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.purpleAccent[700],
child: Icon(Icons.add),
onPressed: _addTodo,
),
);
}
}
when I run the app i get this error
E/flutter ( 7476): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)]
Unhandled Exception: type 'List<dynamic>' is not a subtype of type
'Map<dynamic, dynamic>'
E/flutter ( 7476): #0
_TodoListScreenState._getTodoFromSharedPreferences
(package:flutter_todo/UI/todo_list_screen.dart:70:11)
E/flutter ( 7476): <asynchronous suspension>
E/flutter ( 7476): #1 _TodoListScreenState.initState
(package:flutter_todo/UI/todo_list_screen.dart:29:6)
E/flutter ( 7476): #2 StatefulElement._firstBuild
(package:flutter/src/widgets/framework.dart:3851:58)
E/flutter ( 7476): #3 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #4 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #5 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #6 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #7 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #8 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #9 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #10 Element.rebuild
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #11 ComponentElement._firstBuild
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #12 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #13 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #14 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #15 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #16 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #17 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #18 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #19 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #20 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #21 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #22 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #23 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #24 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #25 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #26 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #27 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #28 Element.rebuild
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #29 ComponentElement._firstBuild
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #30 StatefulElement._firstBuild
(package:flutter/src/widgets/framework.dart:3869:11)
E/flutter ( 7476): #31 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #32 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #33 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #34 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #35 Element.rebuild
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #36 ComponentElement._firstBuild
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #37 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #38 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #39 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #40 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #41 Element.rebuild
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #42 ComponentElement._firstBuild
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #43 StatefulElement._firstBuild
(package:flutter/src/widgets/framework.dart:3869:11)
E/flutter ( 7476): #44 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #45 Ele
I tried to change the List to a Map but didn't succeed
I have succeeded on everything except returning the widget to the screen.
Help me, please :c
I faced this problem before because I wanted to save an array object in shared preferences. You can try this.
//Save you array object as an array of Strings in Shared Preferences
void _saveTodo(List<Todo> todo) async{
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setStringList("savedTodo", _mapTodoData(todo));
}
}
Transform the JSON into an array of Strings
List<String> _mapTodoData(List<dynamic> todos) async{
try {
var res = todos.map((v) => json.encode(v)).toList();
return res;
} catch (err) {
// Just in case
return [];
}
}
}
if you want to get and transform the data in a List of Todo objects
void loadData() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final todoArray = _decodeTodoData(sharedPreferences.getStringList("savedTodo"))
//This is your array :) -> todoArray
}
List<Todo> _decodeTodoData(List<String> todos) {
try {
//Transforming List<String> to Json
var result = todos.map((v) => json.decode(v)).toList();
//Transforming the Json into Array<Todo>
var todObjects = result.map((v) => Todo.fromJson(v)).toList();
return todObjects;
} catch (error) {
return [];
}
}
}
This worked for me, I really struggled with this problem.
I Hope this works for you too.
Here you're trying to iterate over a Map which is not possible because only possible Iterables objects are Set,List and Queue.
// Map MapofTodos = jsonDecode(savedTodo);
//Try to debug it first first and see what type it's returning
print(jsonDecode(savedTodo).runtimeType);
I faced the same issue during app development in dart. The issue with json decoding techniques or might be json conversion.
I have done work around for creating the method as passing the parameter as
getCardData(data[0]["cardContent"][0]["cardData"] as List),
List<String> getCardData(data) {
List<String> _cardInfo = [];
for (int i = 0; i < data.length; i++) {
_cardInfo.add(data[i] as String);
}
return _cardInfo;
}

Drag and Drop List- method 'call' was called on null

I'm trying to make a drag and drop list using flutter_list_drag_and_drop 0.1.6. I've looked for examples of how to implement it, but there aren't any out yet for this specifically, so much of it has been trial and error. Anyway, when I run the app, it gives me an error when trying to drag one of the MyDraggables for the list view. It's says "Exception caught by gesture", "The following NoSuchMethodError was thrown while handling a gesture: The method 'call' was called on null," "Receiver: null", "Tried calling: call(Instance of 'Offset').
I've tried debugging but can not locate where exactly this is crashing. The feedback for the draggable widget is appearing, but stays stuck in place.
```
Widget _buildDragDrop(double _screenHeight, double _screenWidth){
return DragAndDropList(_nonDelList.getList(),
canBeDraggedTo: (int i, int j) {
print("drag to");
// _nonDelList.changePos(_nonDelList.getTaskAt(i), j);
return true;
},
itemBuilder: (BuildContext _context, Task _t1) {
print('Entered Item Builder');
return _buildTask(_t1, _screenHeight, _screenWidth);
},
onDragFinish: (int i, int j){
print('Drag finished');
_nonDelList.changePos(_nonDelList.getTaskAt(i), j);
print('Drag finished 2');
},
dragElevation: 1.5,
);
}
Widget _buildTask(Task _t, double _screenHeight, double
_screenWidth){
final bool alreadyCompleted = !(_t.getPressed());
return new MyDraggable(
child: new ListTile(
title: new Text(_t.getEntry()),
trailing: new Icon(
alreadyCompleted ? Icons.check_box :
Icons.check_box_outline_blank,
color: alreadyCompleted ? _t.getColor() : Colors.black,
),
subtitle: new Text(_t.getDescription()),
),
onDragStarted: (){
print('Started Drag');
},
onMyDraggableCanceled: (Velocity v, Offset o){
print('Drag Canceled');
},
feedback: Material(
shape: CircleBorder(),
child: new InkResponse(
child: Container(
width: _screenWidth / 15.0,
height: _screenWidth / 15.0,
color: Colors.red,
),
),
),
);
}
```
I would expect the list tile to drag and drop in place. The only thing that is happening however, is my feedback is appearing at the top left of the list tile when I start the drag, and then this error is immediately spit out. Also, 'Started Drag' and 'Drag Canceled' are not print out, the only thing that is printing is 'Entered Item Builder.'
I welcome and appreciate all help!
Thanks in advance!
EDIT (Stacktrace)
I/flutter ( 2974): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter ( 2974): The following NoSuchMethodError was thrown while handling a gesture:
I/flutter ( 2974): The method 'call' was called on null.
I/flutter ( 2974): Receiver: null
I/flutter ( 2974): Tried calling: call(Instance of 'Offset')
I/flutter ( 2974):
I/flutter ( 2974): When the exception was thrown, this was the stack:
I/flutter ( 2974): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter ( 2974): #1 DragAvatar.updateDrag
package:flutter_list_drag_and_drop/my_draggable.dart:547
I/flutter ( 2974): #2 new DragAvatar
package:flutter_list_drag_and_drop/my_draggable.dart:498
I/flutter ( 2974): #3 MyDraggableState._startDrag
package:flutter_list_drag_and_drop/my_draggable.dart:328
I/flutter ( 2974): #4 MultiDragGestureRecognizer._startDrag.<anonymous closure>
package:flutter/…/gestures/multidrag.dart:263
I/flutter ( 2974): #5 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:120
I/flutter ( 2974): #6 MultiDragGestureRecognizer._startDrag
package:flutter/…/gestures/multidrag.dart:263
I/flutter ( 2974): #7 MultiDragGestureRecognizer.acceptGesture.<anonymous closure>
package:flutter/…/gestures/multidrag.dart:253
I/flutter ( 2974): #8 _ImmediatePointerState.accepted
package:flutter/…/gestures/multidrag.dart:315
I/flutter ( 2974): #9 MultiDragGestureRecognizer.acceptGesture
package:flutter/…/gestures/multidrag.dart:253
I/flutter ( 2974): #10 GestureArenaManager._resolveInFavorOf
package:flutter/…/gestures/arena.dart:263
I/flutter ( 2974): #11 GestureArenaManager._resolve
package:flutter/…/gestures/arena.dart:222
I/flutter ( 2974): #12 GestureArenaEntry.resolve
package:flutter/…/gestures/arena.dart:52
I/flutter ( 2974): #13 MultiDragPointerState.resolve
package:flutter/…/gestures/multidrag.dart:62
I/flutter ( 2974): #14 _ImmediatePointerState.checkForResolutionAfterMove
package:flutter/…/gestures/multidrag.dart:310
I/flutter ( 2974): #15 MultiDragPointerState._move
package:flutter/…/gestures/multidrag.dart:81
I/flutter ( 2974): #16 MultiDragGestureRecognizer._handleEvent
package:flutter/…/gestures/multidrag.dart:227
I/flutter ( 2974): #17 PointerRouter._dispatch
package:flutter/…/gestures/pointer_router.dart:73
I/flutter ( 2974): #18 PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:101
I/flutter ( 2974): #19 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:214
I/flutter ( 2974): #20 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:192
I/flutter ( 2974): #21 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent
package:flutter/…/gestures/binding.dart:149
I/flutter ( 2974): #22 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue
I/flutter ( 2974): #23 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:85
I/flutter ( 2974): #27 _invoke1 (dart:ui/hooks.dart:223:10)
I/flutter ( 2974): #28 _dispatchPointerDataPacket (dart:ui/hooks.dart:144:5)
I/flutter ( 2974): (elided 3 frames from package dart:async)
I/flutter ( 2974):
I/flutter ( 2974): Handler: onStart
I/flutter ( 2974): Recognizer:
I/flutter ( 2974): ImmediateMultiDragGestureRecognizer#774eb
The stack trace says:
I/flutter ( 2974): When the exception was thrown, this was the stack:
I/flutter ( 2974): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter ( 2974): #1 DragAvatar.updateDrag
package:flutter_list_drag_and_drop/my_draggable.dart:547
Okay, so the null pointer exception occurred there. Let's take a look at the code:
onMove(globalPosition);
That fits the error message, which was:
I/flutter ( 2974): Tried calling: call(Instance of 'Offset')
So globalPosition is likely an Offset, and onMove must be an object. Let's search in the code where onMove was supposed to be set:
DragAvatar({
#required this.overlayState,
...
this.onMove,
(line 491)
which (omitting some steps) appears to be obtained from:
const MyDraggable({
Key key,
#required this.child,
#required this.feedback,
...
this.onMove
(line 101)
I don't see anywhere else where onMove is otherwise set. It looks like there's probably a bug that DragAvatar.updateDrag unconditionally calls onMove, that onMove isn't marked #required initially, or that onMove isn't initialized to some default.
At any rate, try supplying an onMove callback when constructing MyDraggable.
(Alternatively, perhaps consider using the official ReorderableListView class, which the flutter_list_drag_and_drop package page even refers to.)

How to run task in background even if the app is closed and get the latest result generated by the task and display it when app is opened?

I want to to create a step counter app in flutter so i used Flutter pedometer plugin and it worked perfectly, but i want to run this plugin every time to calculate user steps even if the main app is closed .
I found that i can use dart isolates to create a task that can run in another thread away from main thread and communicate between them through ports .
String _stepCountValue = '0';
ReceivePort _receivePort;
Isolate isolate;
iniState() {
super.initState();
_start();
}
void _start() async {
_receivePort = ReceivePort();
isolate = await Isolate.spawn(initPlatformState,
_receivePort.sendPort);
_receivePort.listen((data) {
print(data);
setState(() {
_stepCountValue = "$data";
});
}, onDone: () {
print("done!");
});
}
static void initPlatformState(SendPort sendPort) async {
Pedometer pedometer = new Pedometer();
pedometer.stepCountStream.listen((int stepCountValue) {
print("------------------> $stepCountValue");
sendPort.send(stepCountValue);
}, onError: (error){print(error);}, onDone: (){}, cancelOnError:
true);
}
I expect the output to be the number of user steps .
but i get that error
I/flutter (26151): ══╡ EXCEPTION CAUGHT BY SERVICES LIBRARY ╞══════════════════════════════════════════════════════════
I/flutter (26151): The following _CompileTimeError was thrown while activating platform stream on channel
I/flutter (26151): pedometer.eventChannel:
I/flutter (26151): error: native function 'Window_sendPlatformMessage' (4 arguments) cannot be found
I/flutter (26151): When the exception was thrown, this was the stack:
I/flutter (26151): #0 Window.sendPlatformMessage (dart:ui/window.dart:868:9)
I/flutter (26151): #1 BinaryMessages._sendPlatformMessage (package:flutter/src/services/platform_messages.dart:46:15)
I/flutter (26151): #2 BinaryMessages.send (package:flutter/src/services/platform_messages.dart:97:12)
I/flutter (26151): #3 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:295:50)
I/flutter (26151): <asynchronous suspension>
I/flutter (26151): #4 EventChannel.receiveBroadcastStream.<anonymous closure> (package:flutter/src/services/platform_channel.dart:490:29)
I/flutter (26151): <asynchronous suspension>
I/flutter (26151): #12 StepCounterState.initPlatformState (package:stepcounter/main.dart:59:30)
I/flutter (26151): <asynchronous suspension>
I/flutter (26151): #13 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:303:17)
I/flutter (26151): #14 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)
I/flutter (26151): (elided 7 frames from package dart:async)

how to change app theme in runtime in Flutter?

In my simple project , there is a button to change theme form light to dark and vice versa as below :
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
MyAppState createState() {
return new MyAppState();
}
}
class MyAppState extends State<MyApp> {
Future<bool> load(String key, bool defaultValue) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool state = prefs.getBool(key) ?? defaultValue;
return state;
}
Future<void> save(String key, bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool(key, value);
}
bool state;
#override
Widget build(BuildContext context) {
load("themeKey", false).then((bool value) {
state = value;
});
debugPrint(
"..............state is : " + state.toString() + "...............");
return MaterialApp(
theme: state ? ThemeData.light() : ThemeData.dark(),
home: Scaffold(
body: Container(
child: RaisedButton(
child: Text("change"),
onPressed: () {
setState(() {
state = !state;
});
save("themeKey", state);
},
),
),
),
);
}
}
I use shared_preferences plugin to save the current theme state for the next app launch , but there is a problem it seems that app loads before shared preference loads so i am getting this exception:
Launching lib\main.dart on C1905 in debug mode...
Built build\app\outputs\apk\debug\app-debug.apk.
I/flutter ( 8045): ..............state is : null...............
I/flutter ( 8045): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 8045): The following assertion was thrown building MyApp(dirty, state: MyAppState#6774f):
I/flutter ( 8045): Failed assertion: boolean expression must not be null
I/flutter ( 8045): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 8045): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 8045): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 8045): https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 8045): When the exception was thrown, this was the stack:
I/flutter ( 8045): #0 MyAppState.build (package:test_shared_preferenced/main.dart:36:14)
I/flutter ( 8045): #1 StatefulElement.build (package:flutter/src/widgets/framework.dart:3787:27)
I/flutter ( 8045): #2 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3699:15)
I/flutter ( 8045): #3 Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 8045): #4 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3679:5)
I/flutter ( 8045): #5 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3826:11)
I/flutter ( 8045): #6 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3674:5)
I/flutter ( 8045): #7 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 8045): #8 Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 8045): #9 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:909:16)
I/flutter ( 8045): #10 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:880:5)
I/flutter ( 8045): #11 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:826:17)
I/flutter ( 8045): #12 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2266:19)
I/flutter ( 8045): #13 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:825:13)
I/flutter ( 8045): #14 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:712:7)
I/flutter ( 8045): #15 runApp (package:flutter/src/widgets/binding.dart:756:7)
I/flutter ( 8045): #16 main (package:test_shared_preferenced/main.dart:5:16)
I/flutter ( 8045): #17 _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:289:19)
I/flutter ( 8045): #18 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
I/flutter ( 8045): ════════════════════════════════════════════════════════════════════════════════════════════════════
so what should i do in this situation , please help
The load method is returns a Future that will run asynchronously from the rest of your code. When execution reaches debugPrint or the subsequent return statement, you cannot be guaranteed that the then block has completed its execution. The error you are receiving confirms this. The state boolean has not been set to a value yet - it is still null.
Using a FutureBuilder can help you handle cases where you are waiting on a Future to build your widget tree.
https://www.dartlang.org/tutorials/language/futures is worthwhile reading.

Subtitle in AppBar

I have a SliverAppBar with title and subtitle like this:
SliverAppBar(
backgroundColor: Colors.white,
forceElevated: true,
elevation: 1.0,
pinned: true,
floating: true,
snap: false,
title: Column(
children: <Widget>[
Container(padding: EdgeInsets.only(top: 6.0, bottom: 5.0),
child: Text('Contest', style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500))),
Text(_getFiltersString(), style: TextStyle(fontSize: 14.0, color: Colors.grey[700]),)
]),
It runs but if i scroll i receive this error:
I/flutter ( 4765): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 4765): The following message was thrown during layout:
I/flutter ( 4765): A RenderFlex overflowed by 30 pixels on the bottom.
I/flutter ( 4765):
I/flutter ( 4765): The overflowing RenderFlex has an orientation of Axis.vertical.
I/flutter ( 4765): The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and
I/flutter ( 4765): black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
I/flutter ( 4765): Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the
I/flutter ( 4765): RenderFlex to fit within the available space instead of being sized to their natural size.
I/flutter ( 4765): This is considered an error condition because it indicates that there is content that cannot be
I/flutter ( 4765): seen. If the content is legitimately bigger than the available space, consider clipping it with a
I/flutter ( 4765): ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex,
I/flutter ( 4765): like a ListView.
I/flutter ( 4765): The specific RenderFlex in question is:
I/flutter ( 4765): RenderFlex#968e7 relayoutBoundary=up14 OVERFLOWING
I/flutter ( 4765): creator: Column ← Semantics ← DefaultTextStyle ← LayoutId-[<_ToolbarSlot.middle>] ←
I/flutter ( 4765): CustomMultiChildLayout ← NavigationToolbar ← DefaultTextStyle ← IconTheme ← Builder ←
I/flutter ( 4765): CustomSingleChildLayout ← ClipRect ← ConstrainedBox ← ⋯
I/flutter ( 4765): parentData: <none> (can use size)
I/flutter ( 4765): constraints: BoxConstraints(0.0<=w<=176.0, 0.0<=h<=20.3)
I/flutter ( 4765): size: Size(70.0, 20.3)
I/flutter ( 4765): direction: vertical
I/flutter ( 4765): mainAxisAlignment: start
I/flutter ( 4765): mainAxisSize: max
I/flutter ( 4765): crossAxisAlignment: center
I/flutter ( 4765): verticalDirection: down
I/flutter ( 4765): ◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤
I/flutter ( 4765): ════════════════════════════════════════════════════════════════════════════════════════════════════
Reloaded 32 of 722 libraries in 2.887ms.
What i have to use instead of Column?
Thanks
This means that the widget is bigger than the view. Now what you can do is wrap the Column in a SingleChildScrollView to let it scroll:
SingleChildScrollView( child: Column(...) )

Resources