Chuyển đến nội dung

Bài 69 · Projects

Projects: Fitness, Event Calendar, Image Compressor, Portfolio

Four Flutter projects with real code: a fitness tracker with streaks, an event calendar with table_calendar, an image compressor, and a link-in-bio portfolio page.

The first mini projects were self-contained. These four lean on packages and platform features, so they feel more like real apps: a fitness tracker that stores daily activity and counts streaks, an event calendar with markers on days that have events, an image compressor that shrinks photos before upload, and a portfolio page of links. Each has one tricky idea that deserves a closer look, and each of those ideas is plain logic we can run.

Real vs stand-in. The Dart is real and read-only, because the site cannot run Flutter or its plugins. Package APIs change over time, so check pub.dev for the versions you install. The live examples are JavaScript stand-ins of the tricky logic: streak counting, comparing calendar days, and choosing compression settings.

Project 1: Fitness tracker

What you practice: a data model, local storage, a list grouped by day, and derived statistics.

The model is one record per day. Store them with shared_preferences as JSON for a first version, or with SQLite/Drift when history grows (local storage).

DART
class DayLog {
  const DayLog({required this.date, required this.steps, required this.minutes});
  final DateTime date;   // date only, time ignored
  final int steps;
  final int minutes;

  Map<String, dynamic> toJson() => {'date': date.toIso8601String(), 'steps': steps, 'minutes': minutes};
  factory DayLog.fromJson(Map<String, dynamic> j) =>
      DayLog(date: DateTime.parse(j['date'] as String), steps: j['steps'] as int, minutes: j['minutes'] as int);
}

class FitnessController extends ChangeNotifier {
  final List<DayLog> _logs = [];
  List<DayLog> get logs => List.unmodifiable(_logs);

  void add(DayLog log) {
    _logs.removeWhere((l) => _sameDay(l.date, log.date));   // one entry per day
    _logs.add(log);
    _logs.sort((a, b) => b.date.compareTo(a.date));
    notifyListeners();
    // persist(...) here
  }

  int get todaySteps => _logs.where((l) => _sameDay(l.date, DateTime.now())).fold(0, (s, l) => s + l.steps);
}

bool _sameDay(DateTime a, DateTime b) => a.year == b.year && a.month == b.month && a.day == b.day;

Expose the controller with Provider (Provider) and show today's goal with a CircularProgressIndicator(value: todaySteps / 10000). The tricky part is the streak: how many consecutive days, ending today (or yesterday if today is not logged yet), met the goal.

JS Counting a daily streak

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice a design decision: an unfinished today does not break the streak, which is kinder to users. A product choice like that belongs in a tested function, not in the widget.

Project 2: Event calendar

What you practice: a third-party widget, a map of events by day, and date-only comparison.

table_calendar draws a month grid and lets you attach events and handle selection.

DART
class EventCalendar extends StatefulWidget {
  const EventCalendar({super.key});
  @override
  State<EventCalendar> createState() => _EventCalendarState();
}

class _EventCalendarState extends State<EventCalendar> {
  DateTime _focused = DateTime.now();
  DateTime? _selected;
  final Map<DateTime, List<String>> _events = {};

  DateTime _day(DateTime d) => DateTime.utc(d.year, d.month, d.day);   // normalize

  List<String> _eventsFor(DateTime day) => _events[_day(day)] ?? const [];

  void _add(String title) {
    final key = _day(_selected ?? _focused);
    setState(() => _events.update(key, (list) => [...list, title], ifAbsent: () => [title]));
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TableCalendar<String>(
          firstDay: DateTime.utc(2020, 1, 1),
          lastDay: DateTime.utc(2035, 12, 31),
          focusedDay: _focused,
          selectedDayPredicate: (d) => isSameDay(_selected, d),
          eventLoader: _eventsFor,
          onDaySelected: (selected, focused) => setState(() { _selected = selected; _focused = focused; }),
          onPageChanged: (focused) => _focused = focused,
        ),
        Expanded(
          child: ListView(
            children: [for (final e in _eventsFor(_selected ?? _focused)) ListTile(title: Text(e))],
          ),
        ),
      ],
    );
  }
}

The package hands you DateTimes with various times and time zones, but your map keys must match exactly. The bug everyone hits: DateTime(2026, 3, 14, 18, 30) is not equal to DateTime(2026, 3, 14), so a map lookup misses. Normalize every key to a UTC midnight (DateTime.utc(y, m, d)) when you store and when you read, and use the package's isSameDay for comparison.

JS Date keys that match

Press Run (or Ctrl + Enter) to see the console output here.

No output.

To persist events, store a list per ISO date string, and think about time zones: an event at 23:30 local is on the next day in UTC. Decide whether your calendar is "floating" local dates (most personal apps) or absolute instants (meetings across zones).

Project 3: Image compressor

What you practice: picking files (image picker), platform plugins, and showing before/after sizes.

DART
import 'package:flutter_image_compress/flutter_image_compress.dart';

class Compressed {
  const Compressed(this.bytes, this.originalSize);
  final Uint8List bytes;
  final int originalSize;
  double get ratio => bytes.length / originalSize;
}

Future<Compressed?> compress(String path, {int quality = 80, int maxSide = 1600}) async {
  final original = await File(path).length();
  final bytes = await FlutterImageCompress.compressWithFile(
    path,
    quality: quality,
    minWidth: maxSide,     // the plugin scales so neither side is below these,
    minHeight: maxSide,    // so for a maximum, resize first or use cacheWidth below
    format: CompressFormat.jpeg,
  );
  return bytes == null ? null : Compressed(bytes, original);
}

The screen lets the user pick a photo with image_picker, calls compress, shows Image.memory(result.bytes) and text like "3.2 MB to 410 KB (13%)". A quality slider re-runs the compression. Two facts shape good settings: pixel dimensions matter more than quality (an 8000-pixel-wide photo shown on a phone screen is wasted data), and JPEG quality below roughly 60 shows visible artifacts. For display only, you can also decode smaller with Image.file(file, cacheWidth: 800) to save memory (image caching). Compression runs in native code, so it does not block the UI isolate, but still show a progress indicator.

JS Pick dimensions and quality for a size budget

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If the platform call has a size budget (an upload limit), loop: resize, compress at 85, and lower the quality in steps until the byte length fits or you reach a floor. Wrap it in a try/catch: unsupported formats (some HEIC files, animated GIFs) return null or throw.

What you practice: layout, theming, responsive width and url_launcher.

A single scrolling page: avatar, name, short bio, and a column of link buttons. It should look good on a phone and on a wide desktop browser (Flutter on the web), so center it in a constrained column.

DART
class LinkItem {
  const LinkItem(this.label, this.icon, this.url);
  final String label;
  final IconData icon;
  final String url;
}

const links = [
  LinkItem('GitHub', Icons.code, 'https://github.com/example'),
  LinkItem('Blog', Icons.edit_note, 'https://example.com/blog'),
  LinkItem('Email me', Icons.mail, 'mailto:[email protected]'),
];

class PortfolioPage extends StatelessWidget {
  const PortfolioPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: ConstrainedBox(
            constraints: const BoxConstraints(maxWidth: 480),
            child: ListView(
              padding: const EdgeInsets.all(24),
              children: [
                const CircleAvatar(radius: 56, backgroundImage: AssetImage('assets/me.jpg')),
                const SizedBox(height: 16),
                Text('Sam Rivera', textAlign: TextAlign.center, style: Theme.of(context).textTheme.headlineMedium),
                const Text('Mobile developer. I build Flutter apps.', textAlign: TextAlign.center),
                const SizedBox(height: 24),
                for (final item in links)
                  Padding(
                    padding: const EdgeInsets.only(bottom: 12),
                    child: FilledButton.tonalIcon(
                      icon: Icon(item.icon),
                      label: Text(item.label),
                      onPressed: () => launchUrl(Uri.parse(item.url), mode: LaunchMode.externalApplication),
                    ),
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

The ConstrainedBox with maxWidth is the key to responsive design here, as explained in Responsive and adaptive layouts. Launching mailto: links, phone numbers and web pages is covered in Launching URLs, Email, SMS and Phone Calls. For the SEO and sharing a real portfolio needs, remember that a Flutter web app is a canvas: a plain HTML page is better for search ranking.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why does a calendar map lookup fail when the key is a DateTime with a time of day?

    Equality includes the time, so store and read with a normalized day (for example DateTime.utc(y, m, d)).
  2. 2. In the streak logic, why is a day without a log yet not counted as a break when it is today?

    Counting back from yesterday avoids resetting someone's streak before they have had a chance to act.
  3. 3. What usually saves more bytes when compressing a photo for upload?

    A huge image displayed small wastes pixels. Resize, then tune quality.
  4. 4. How does the portfolio page stay readable on a wide desktop screen?

    A maximum width keeps the column narrow and centered however wide the window is.

Summary

  • The fitness tracker models one record per day, stores it locally and derives a streak with a clear, tested rule.
  • The calendar needs normalized date keys, or lookups silently miss.
  • The image compressor resizes first, then lowers quality until a size budget is met, and must handle unsupported files.
  • The portfolio page combines a constrained column, themed buttons and url_launcher.

Next: Practice Exercises with Solutions

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.