Skip to content

Instantly share code, notes, and snippets.

@asialgearoid
Created May 30, 2018 03:19
Show Gist options
  • Save asialgearoid/2199125c027a9cbaee9738e3e985e50e to your computer and use it in GitHub Desktop.
Save asialgearoid/2199125c027a9cbaee9738e3e985e50e to your computer and use it in GitHub Desktop.
Todo App Step 3 (Modifying State)
class TodoListState extends State<TodoList> {
List<String> _todoItems = [];
// This will be called each time the + button is pressed
void _addTodoItem() {
// Putting our code inside "setState" tells the app that our state has changed, and
// it will automatically re-render the list
setState(() {
int index = _todoItems.length;
_todoItems.add('Item ' + index.toString());
});
}
// Build the whole list of todo items
Widget _buildTodoList() {
return new ListView.builder(
itemBuilder: (context, index) {
// itemBuilder will be automatically be called as many times as it takes for the
// list to fill up its available space, which is most likely more than the
// number of todo items we have. So, we need to check the index is OK.
if(index < _todoItems.length) {
return _buildTodoItem(_todoItems[index]);
}
},
);
}
// Build a single todo item
Widget _buildTodoItem(String todoText) {
return new ListTile(
title: new Text(todoText)
);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Todo List')
),
body: _buildTodoList(),
floatingActionButton: new FloatingActionButton(
onPressed: _addTodoItem,
tooltip: 'Add task',
child: new Icon(Icons.add)
),
);
}
}
@ttusk
Copy link

ttusk commented Feb 5, 2023

At line 17 i get an error from vsc saying: Error: A non-null value must be returned since the return type 'Widget' doesn't allow null.

  • 'Widget' is from 'package:flutter/src/widgets/framework.dart'
    ('../../Documents/flutter/packages/flutter/lib/src/widgets/framework.dart').
    itemBuilder: (context, index) {

The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type. Try adding either a return or a throw statement at the end. (dartbody_might_complete_normally)

Did you manage to fix it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment