Menu
CoddyTech

רשימת משימות: מצבים ריקים

חלק מהיחידה פרויקטים במסלול ה-Flutter של Coddy. שיעור 9 מתוך 36.

לוחצים על Done לפני שמסיימים משהו, ומקבלים מסך ריק. האם משהו התקלקל, או שאין שם כלום? מצב ריק עונה על כך: סמל שקט ושורה שמסבירה מה קורה.

לכל מסנן יש הודעה משלו, ולכן ביטוי switch על _filter בוחר אותה:

String get _emptyMessage => switch (_filter) {
  Filter.all => 'No tasks yet',
  Filter.active => 'Nothing left to do',
  Filter.done => 'Nothing done yet',
};

לאחר מכן, במקום שבו מוצגת הרשימה מופיע אחד משני הדברים: shown.isEmpty ? Center(...) : ListView.builder(...). בודקים את הרשימה שמוצגת, ולא את _tasks: במסנן Done, הרשימה המלאה אינה ריקה, אבל המסך כן.

מגדירים לסמל את צבע ה־outline של ערכת הנושא: Theme.of(context).colorScheme.outline. זהו הגוון האפור והרך של צבע הבסיס שלך, ולכן המצב הריק נראה כחלק מהאפליקציה.

זהו השיעור האחרון ברשימת המטלות. הבדיקות בוחנות את האפליקציה כולה: הוספה, סימון, החלקה וסינון.

challenge icon

אתגר

בינוני

הצג מצב ריק כאשר shown ריק:

  • הוסף getter בשם _emptyMessage: No tasks yet עבור הכול, Nothing left to do עבור פעילות, Nothing done yet עבור הושלמו
  • במקום הרשימה, הצג Column ממורכזת ובה סמל Icons.task_alt (בגודל 64, בצבע outline של ערכת הנושא), רווח של 12 פיקסלים וההודעה
  • אחרת, הצג את הרשימה כמו קודם

נסו בעצמכם

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,
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה פרויקטים

תרגלו בעצמכם: קומפיילר Flutter אונליין