完成イメージ
コード
main に書き連ねているだけのサンプルです。
main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: TodoList(),
);
}
}
class TodoList extends StatefulWidget {
@override
TodoListState createState() => TodoListState();
}
class TodoListState extends State<TodoList> {
List<String> _todoItems = ['task1', 'task2', 'task3', 'task4'];
void _addTodoItem(String task) {
if (task.length > 0) {
setState(() => _todoItems.insert(0, task));
}
}
Widget _buildTodoList() {
return ListView.separated(
itemCount: _todoItems.length,
itemBuilder: (context, index) {
return _buildTodoItem(
context,
_todoItems[index],
index
);
},
separatorBuilder: (context, index) {
return Divider();
},
);
}
Widget _buildTodoItem(BuildContext context, String todoText, int index) {
return Dismissible(
// Show a red background as the item is swiped away.
background: Container(color: Colors.red),
key: Key(todoText),
onDismissed: (direction) {
setState(() {
_todoItems.removeAt(index);
});
Scaffold
.of(context)
.showSnackBar(SnackBar(content: Text("$todoText dismissed")));
},
child: ListTile(title: Text(todoText)),
);
}
Widget _floatingButton() {
return FloatingActionButton(
onPressed: () => {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Scaffold(
appBar: AppBar(title: Text('New task'),),
body: TextField(
autofocus: true,
onSubmitted: (val) {
_addTodoItem(val);
Navigator.pop(context);
},
decoration: InputDecoration(
hintText: 'タスクをどうぞ',
contentPadding: const EdgeInsets.all(16.0),
)
),
)
)
)
},
child: Icon(Icons.add)
);
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Todo')),
body: _buildTodoList(),
floatingActionButton: _floatingButton(),
);
}
}
参考
https://medium.com/the-web-tub/making-a-todo-app-with-flutter-5c63dab88190
https://pusher.com/tutorials/flutter-listviews
https://flutter.dev/docs/cookbook/navigation/navigation-basics
https://flutter.dev/docs/cookbook/gestures/dismissible