Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 73 ยท Projects

Projects: Calculator, BMI, Tic-Tac-Toe, Quiz and Magic 8 Ball

Five small Flutter projects with real Dart code: a calculator, a BMI app, tic-tac-toe, an API-driven quiz and a magic 8 ball, each with its logic separated and testable.

Small projects are where Flutter concepts stop being separate lessons and start fitting together. This lesson builds five tiny apps. Each one practices the same habit: put the logic in plain Dart classes that know nothing about widgets, and keep the widgets thin. Logic in plain Dart is easy to test (unit and widget testing), and it is exactly the part the live stand-ins below can run.

Real vs stand-in. The Dart is real Flutter and read-only, because the site cannot run a Flutter app. The live examples are JavaScript versions of each project's logic (same algorithm, same results). Port them back to Dart classes and your widgets only call them.

Project 1: Calculator

What you practice: a grid of buttons, a display, and parsing an expression with correct operator precedence (2 + 3 * 4 is 14, not 20).

The widget side is a GridView.count of buttons that append characters to a string, plus = and C:

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

class _CalculatorScreenState extends State<CalculatorScreen> {
  String _expression = '';
  String _result = '';

  static const _keys = ['7','8','9','/','4','5','6','*','1','2','3','-','0','.','=','+'];

  void _press(String key) {
    setState(() {
      if (key == '=') {
        try {
          _result = formatNumber(evaluate(_expression));
        } on FormatException catch (e) {
          _result = e.message;
        }
      } else {
        _expression += key;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Calculator')),
      body: Column(
        children: [
          Padding(padding: const EdgeInsets.all(16), child: Text(_expression, style: Theme.of(context).textTheme.headlineMedium)),
          Text(_result, style: Theme.of(context).textTheme.displaySmall),
          const Spacer(),
          GridView.count(
            crossAxisCount: 4,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: [for (final k in _keys) TextButton(onPressed: () => _press(k), child: Text(k, style: const TextStyle(fontSize: 24)))],
          ),
          TextButton(onPressed: () => setState(() { _expression = ''; _result = ''; }), child: const Text('Clear')),
        ],
      ),
    );
  }
}

The interesting part is evaluate. Do not use eval-like tricks. Convert the text into tokens, then use the shunting-yard method: operators with higher precedence are applied first.

JS Expression evaluator with precedence

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

No output.

Project 2: BMI calculator

What you practice: Slider, TextField input, derived values and categories.

Body mass index is weight in kilograms divided by height in meters squared. The widget holds two numbers and shows the result, and the logic is one small class:

DART
enum BmiCategory { underweight, normal, overweight, obese }

class Bmi {
  const Bmi({required this.kg, required this.cm});
  final double kg;
  final double cm;

  double get value {
    final m = cm / 100;
    return kg / (m * m);
  }

  BmiCategory get category => switch (value) {
    < 18.5 => BmiCategory.underweight,
    < 25 => BmiCategory.normal,
    < 30 => BmiCategory.overweight,
    _ => BmiCategory.obese,
  };
}

In the UI, two Sliders update _kg and _cm with setState, and Text(Bmi(kg: _kg, cm: _cm).value.toStringAsFixed(1)) shows the result live. Add a disclaimer: BMI is a rough screening number, not medical advice, and the thresholds above are the adult ranges. Children and athletes need different interpretation.

Project 3: Tic-Tac-Toe

What you practice: a 3x3 GridView, an immutable board, winner detection, and a simple computer opponent.

The board is a list of nine cells. All eight winning lines are listed once, so checking a winner is a loop:

DART
const lines = [
  [0, 1, 2], [3, 4, 5], [6, 7, 8],   // rows
  [0, 3, 6], [1, 4, 7], [2, 5, 8],   // columns
  [0, 4, 8], [2, 4, 6],              // diagonals
];

String? winner(List<String> board) {
  for (final [a, b, c] in lines) {
    if (board[a].isNotEmpty && board[a] == board[b] && board[b] == board[c]) return board[a];
  }
  return null;
}

bool isDraw(List<String> board) => winner(board) == null && !board.contains('');

The UI is GridView.builder(itemCount: 9, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), itemBuilder: ...) where each cell is an InkWell calling _play(index). In _play, ignore taps when the cell is taken or the game is over, place the mark, and swap the player.

JS Winner detection and a simple computer move

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

No output.

Project 4: A quiz app with an API

What you practice: HTTP and JSON, FutureBuilder, a model class and scoring.

Fetch questions from a trivia endpoint that returns JSON, turn them into a model, shuffle the answers, and score taps. Public trivia APIs often return text with HTML entities (&quot;), so decode before showing it.

DART
class Question {
  Question({required this.text, required this.answers, required this.correctIndex});
  final String text;
  final List<String> answers;
  final int correctIndex;

  factory Question.fromJson(Map<String, dynamic> json) {
    final correct = json['correct_answer'] as String;
    final answers = [...(json['incorrect_answers'] as List).cast<String>(), correct]..shuffle();
    return Question(
      text: json['question'] as String,
      answers: answers,
      correctIndex: answers.indexOf(correct),
    );
  }
}

Future<List<Question>> fetchQuestions() async {
  final res = await http.get(Uri.parse('https://example.com/api/questions?amount=5'));
  if (res.statusCode != 200) throw Exception('Server returned ${res.statusCode}');
  final data = jsonDecode(res.body) as Map<String, dynamic>;
  return (data['results'] as List).map((j) => Question.fromJson(j as Map<String, dynamic>)).toList();
}

(Replace the URL with the trivia API you choose and read its terms.) The screen keeps _index and _score: show questions[_index], a ListTile per answer, and on tap compare with correctIndex, increase the score, then advance. When _index reaches the end, show the result with a "Play again" button that refetches. Wrap the fetch in a FutureBuilder or load it in initState with a loading and error state.

Project 5: Magic 8 Ball

What you practice: Random, a tap or shake trigger and a small animation.

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

class _Magic8BallState extends State<Magic8Ball> {
  static const _answers = ['It is certain', 'Ask again later', 'Do not count on it', 'Yes, definitely', 'Very doubtful'];
  final _random = Random();
  String _answer = 'Ask me anything';
  bool _thinking = false;

  Future<void> _ask() async {
    setState(() { _thinking = true; });
    await Future<void>.delayed(const Duration(milliseconds: 600));
    setState(() {
      _answer = _answers[_random.nextInt(_answers.length)];
      _thinking = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _thinking ? null : _ask,
      child: Center(
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          width: _thinking ? 200 : 240,
          height: _thinking ? 200 : 240,
          decoration: const BoxDecoration(color: Colors.black, shape: BoxShape.circle),
          alignment: Alignment.center,
          child: Text(_thinking ? '...' : _answer, textAlign: TextAlign.center, style: const TextStyle(color: Colors.white, fontSize: 20)),
        ),
      ),
    );
  }
}

To react to shaking, listen to accelerometer events from sensors_plus and trigger _ask when the acceleration magnitude passes a threshold (cancel the subscription in dispose). A tap fallback matters for accessibility and for simulators (accessibility). Two details worth making testable: pass the Random in so tests can seed it, and never pick an answer while one is already being "thought".

JS Quiz scoring, entity decoding and a seeded 8 ball

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

No output.

Ideas to level up each project

  • Calculator: history list, memory keys, parentheses buttons, a Semantics label per key.
  • BMI: metric and imperial toggle, save past values with local storage.
  • Tic-tac-toe: a minimax opponent, a score board, a win animation with implicit animations.
  • Quiz: categories, a timer per question, a high-score list in a database.
  • 8 ball: a shake gesture and a haptic tap with HapticFeedback.mediumImpact().

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does 2 + 3 * 4 evaluate to 14 in the calculator?

    Shunting-yard applies operators with higher precedence first: 3 * 4 = 12, then 2 + 12.
  2. 2. How is a tic-tac-toe winner detected?

    Three rows, three columns and two diagonals are every possible win.
  3. 3. Why shuffle the answers in the quiz's fromJson factory?

    Otherwise the correct answer would always be last. Keep the index of the right one after shuffling.
  4. 4. What makes the 8 ball logic easy to test?

    A seeded Random gives repeatable results.

Summary

  • Separate logic (evaluator, Bmi, winner, Question) from widgets, so it can be tested without a screen.
  • The calculator needs tokenizing and operator precedence; tic-tac-toe is a list of eight lines; the quiz maps JSON into a model and scores answers; the 8 ball is a guarded random pick.
  • Each project grows naturally into a larger one by adding storage, animation or networking.

Next: Projects: Fitness, Event Calendar, Image Compressor, Portfolio