Lista de tarefas: Estados vazios
Parte da seção Projetos do Journey de Flutter da Coddy. Lição 9 de 36.
Toque em Done antes de terminar qualquer tarefa e você verá uma tela em branco. O app está com defeito ou não há nada lá? Um estado vazio responde a isso: um ícone discreto e uma linha que explica o que está acontecendo.
Cada filtro tem sua própria mensagem, então uma expressão switch em _filter a seleciona:
String get _emptyMessage => switch (_filter) {
Filter.all => 'No tasks yet',
Filter.active => 'Nothing left to do',
Filter.done => 'Nothing done yet',
};Então, no lugar da lista, aparece uma coisa ou outra: shown.isEmpty ? Center(...) : ListView.builder(...). Teste a lista exibida, não _tasks: em Done, a lista completa não está vazia, mas a tela está.
Use para o ícone a cor outline do tema: Theme.of(context).colorScheme.outline. É o tom de cinza suave da cor-base, então o estado vazio parece fazer parte do app.
Esta é a última lição da lista de tarefas. Os testes verificam o app inteiro: adicionar, marcar, deslizar e filtrar.
Desafio
MédioMostre um estado vazio quando shown estiver vazio:
- adicione um getter
_emptyMessage:No tasks yetpara Todas,Nothing left to dopara Ativas,Nothing done yetpara Concluídas - no lugar da lista, mostre uma
Columncentralizada com um íconeIcons.task_alt(tamanho 64, coroutlinedo tema), 12 pixels de espaço e a mensagem - caso contrário, mostre a lista como antes
Experimente você mesmo
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
),
home: const TodoScreen(),
);
}
}
class Task {
Task(this.title);
final String title;
bool done = false;
}
enum Filter { all, active, done }
class TodoScreen extends StatefulWidget {
const TodoScreen({super.key});
@override
State<TodoScreen> createState() => _TodoScreenState();
}
class _TodoScreenState extends State<TodoScreen> {
final List<Task> _tasks = [Task('Buy milk'), Task('Walk the dog'), Task('Read a book')];
final _controller = TextEditingController();
Filter _filter = Filter.all;
int get _left => _tasks.where((task) => !task.done).length;
List<Task> get _shown => switch (_filter) {
Filter.all => _tasks,
Filter.active => _tasks.where((task) => !task.done).toList(),
Filter.done => _tasks.where((task) => task.done).toList(),
};
void _addTask() {
final title = _controller.text.trim();
if (title.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Type a task first')),
);
return;
}
setState(() {
_tasks.add(Task(title));
});
_controller.clear();
}
void _deleteTask(Task task) {
final index = _tasks.indexOf(task);
setState(() {
_tasks.remove(task);
});
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Deleted ${task.title}'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
setState(() {
_tasks.insert(index, task);
});
},
),
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final shown = _shown;
return Scaffold(
appBar: AppBar(title: const Text('My Tasks')),
body: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: const InputDecoration(
labelText: 'New task',
border: OutlineInputBorder(),
),
),
),
const SizedBox(width: 8),
IconButton.filled(
onPressed: _addTask,
icon: const Icon(Icons.add),
),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
children: [
Text(
_left == 1 ? '1 task left' : '$_left tasks left',
style: Theme.of(context).textTheme.titleSmall,
),
],
),
),
SegmentedButton<Filter>(
segments: const [
ButtonSegment(value: Filter.all, label: Text('All')),
ButtonSegment(value: Filter.active, label: Text('Active')),
ButtonSegment(value: Filter.done, label: Text('Done')),
],
selected: {_filter},
onSelectionChanged: (selection) {
setState(() {
_filter = selection.first;
});
},
),
const SizedBox(height: 8),
Expanded(
child: ListView.builder(
itemCount: shown.length,
itemBuilder: (context, index) {
final task = shown[index];
return Dismissible(
key: ObjectKey(task),
direction: DismissDirection.endToStart,
background: Container(
color: Colors.red,
alignment: Alignment.centerRight,
padding: const EdgeInsets.symmetric(horizontal: 24),
child: const Icon(Icons.delete, color: Colors.white),
),
onDismissed: (direction) => _deleteTask(task),
child: ListTile(
leading: Checkbox(
value: task.done,
onChanged: (value) {
setState(() {
task.done = value!;
});
},
),
title: Text(
task.title,
style: task.done
? const TextStyle(
decoration: TextDecoration.lineThrough,
color: Colors.grey,
)
: null,
),
),
);
},
),
),
],
),
);
}
}
Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.
Todas as lições de Projetos
1Projeto: Lista de tarefas
Lista de tarefas: A lista de tarefasLista de tarefas: Adicione uma tarefa4Projeto: Rastreador de Hábitos
Rastreador de Hábitos: Seus hábitosRastreador de Hábitos: A semanaPratique por conta própria: Compilador de Flutter online