Of course! This is an excellent project for learning Flutter because it touches on several core concepts: UI, state management, asset handling, and networking.
Let's break down how to build this multiplayer quiz app. I'll teach the basics as we go.
Flutter Basics: The Core Concepts
- Everything is a Widget: In Flutter, your entire UI—from a button to the screen padding to the layout itself—is a widget. You build your app by composing widgets inside other widgets, creating a "widget tree."
- Stateless vs. Stateful Widgets:
StatelessWidget: A widget that cannot change its internal state once built. Think of a title or an icon.
StatefulWidget: A widget that can change its state during its lifetime. Our quiz screen is a perfect example, as it needs to track the current question, the timer, and the selected answer.
main.dart: This is the entry point of your app. It calls runApp() to start your main widget.
pubspec.yaml: This file is your project's "recipe." It lists dependencies (like packages for networking), assets (like images or our JSON file), and other project metadata.
The Multiplayer Challenge: Real-time Sync
The hardest part of your request is making the game synchronized for all players. When the host clicks "Next Question," everyone's screen must update instantly.
A simple app can't do this on its own. It needs a backend server to act as the "single source of truth."
For this tutorial, the perfect beginner-friendly backend is Firebase Firestore. It's a real-time NoSQL database from Google. When data changes in Firestore, it automatically pushes the update to all connected apps. This is exactly what we need.
Let's Build the Quiz App: Step-by-Step
Step 1: Project Setup
- Install Flutter: If you haven't already, follow the official Flutter installation guide.
- Create a New Project: Open your terminal or command prompt and run:
flutter create multi_quiz_app
cd multi_quiz_app
- Add Dependencies: Open the
pubspec.yaml file and add the following packages under dependencies:
dependencies:
flutter:
sdk: flutter
# For connecting to Firebase
firebase_core: ^2.27.0
# For using the real-time database
cloud_firestore: ^4.15.8
# For nice random IDs
uuid: ^4.4.0
After saving the file, run flutter pub get in your terminal to install them.
Step 2: Firebase Setup
- Go to the Firebase Console and create a new project.
- Connect your Flutter app: Follow the instructions in the Firebase project settings to connect your app. You will need to use the Firebase CLI (Command Line Interface).
# Install the Firebase CLI if you haven't
dart pub global activate flutterfire_cli
# Run this command from your Flutter project's root directory
flutterfire configure
This will automatically configure your app for Android, iOS, and Desktop.
- Enable Firestore: In the Firebase console, go to "Firestore Database," click "Create database," start in test mode (this allows open access for now), and choose a server location.
Step 3: Data Structure in Firestore
We need to decide how to store our game data. In Firestore, we'll have a games collection. Each game will be a document inside that collection.
A game document will look like this:
{
"gameState": "lobby", // "lobby", "in_progress", "finished"
"currentQuestionIndex": 0,
"players": {
"player_id_1": { "name": "Alice", "score": 0 },
"player_id_2": { "name": "Bob", "score": 0 }
},
"questions": [ /* Our list of questions will go here */ ]
}
Step 4: Load Questions from JSON
- In the root of your project, create a new folder called
assets.
- Inside
assets, create a file named questions.json.
- Paste the following JSON data into it:
[
{
"question": "What is the capital of France?",
"options": ["Berlin", "Madrid", "Paris", "Rome"],
"answer": "Paris"
},
{
"question": "Which widget is the entry point of a Flutter app?",
"options": ["Scaffold", "MaterialApp", "Container", "Text"],
"answer": "MaterialApp"
}
]
(You can add all 12 of your questions here.)
- Tell Flutter about the asset: In
pubspec.yaml, add the following:
flutter:
uses-material-design: true
assets:
- assets/questions.json # This line is important!
Step 5: Coding the App (The Fun Part!)
We'll structure our app into several screens:
main.dart: App initialization.
home_screen.dart: Create or Join a game.
lobby_screen.dart: Wait for players to join. Host can start the game.
quiz_screen.dart: The actual quiz gameplay.
leaderboard_screen.dart: Show the final scores.
Here's a simplified version of the code to get you started.
lib/main.dart
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart'; // This is auto-generated by flutterfire
import 'home_screen.dart';
void main() async {
// Ensure Flutter and Firebase are initialized before running the app
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Multiplayer Quiz',
theme: ThemeData(
primarySwatch: Colors.purple,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomeScreen(), // Our starting screen
);
}
}
lib/home_screen.dart
This screen lets you choose to be a Host or a Player.
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
import 'package:uuid/uuid.dart';
import 'lobby_screen.dart'; // We will create this next
class HomeScreen extends StatelessWidget {
final TextEditingController _nameController = TextEditingController();
final TextEditingController _gameIdController = TextEditingController();
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final Uuid _uuid = Uuid();
// Host creates a new game
Future<void> _createGame(BuildContext context) async {
final String playerName = _nameController.text.trim();
if (playerName.isEmpty) return;
final String gameId = _uuid.v4().substring(0, 6).toUpperCase(); // A simple 6-char ID
final String playerId = _uuid.v4();
// Load questions from JSON
final String questionsJsonString = await rootBundle.loadString('assets/questions.json');
final List<dynamic> questions = json.decode(questionsJsonString);
await _firestore.collection('games').doc(gameId).set({
'gameState': 'lobby',
'currentQuestionIndex': 0,
'players': {
playerId: {'name': playerName, 'score': 0}
},
'questions': questions,
});
Navigator.push(context, MaterialPageRoute(builder: (_) => LobbyScreen(gameId: gameId, playerId: playerId)));
}
// Player joins an existing game
Future<void> _joinGame(BuildContext context) async {
final String playerName = _nameController.text.trim();
final String gameId = _gameIdController.text.trim().toUpperCase();
if (playerName.isEmpty || gameId.isEmpty) return;
final String playerId = _uuid.v4();
// Add player to the game
await _firestore.collection('games').doc(gameId).update({
'players.$playerId': {'name': playerName, 'score': 0}
});
Navigator.push(context, MaterialPageRoute(builder: (_) => LobbyScreen(gameId: gameId, playerId: playerId)));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Flutter Quiz')),
body: Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(controller: _nameController, decoration: InputDecoration(labelText: 'Your Name')),
SizedBox(height: 20),
// Host controls
ElevatedButton(onPressed: () => _createGame(context), child: Text('Create Game (Host)')),
SizedBox(height: 40),
// Player controls
TextField(controller: _gameIdController, decoration: InputDecoration(labelText: 'Game ID')),
ElevatedButton(onPressed: () => _joinGame(context), child: Text('Join Game')),
],
),
),
),
);
}
}
lib/lobby_screen.dart
This screen uses a StreamBuilder widget. This is a core Flutter concept for reactive UIs. It listens to a stream (in our case, changes from Firestore) and rebuilds itself whenever new data arrives.
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'quiz_screen.dart'; // We'll build this last
class LobbyScreen extends StatelessWidget {
final String gameId;
final String playerId;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
LobbyScreen({required this.gameId, required this.playerId});
void _startGame(BuildContext context) {
_firestore.collection('games').doc(gameId).update({'gameState': 'in_progress'});
}
@override
Widget build(BuildContext context) {
// StreamBuilder listens for real-time updates from our game document
return StreamBuilder<DocumentSnapshot>(
stream: _firestore.collection('games').doc(gameId).snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Scaffold(body: Center(child: CircularProgressIndicator()));
}
var gameData = snapshot.data!.data() as Map<String, dynamic>;
var players = gameData['players'] as Map<String, dynamic>;
// If game starts, navigate all players to the quiz screen
if (gameData['gameState'] == 'in_progress') {
// Use a post-frame callback to navigate safely after the build
WidgetsBinding.instance.addPostFrameCallback((_) {
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => QuizScreen(gameId: gameId, playerId: playerId)));
});
}
bool isHost = players.keys.first == playerId;
return Scaffold(
appBar: AppBar(title: Text('Lobby - Game ID: $gameId')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Players Joined:', style: Theme.of(context).textTheme.headlineSmall),
// Display list of players
...players.entries.map((player) => Text(player.value['name'])).toList(),
SizedBox(height: 40),
// The "Start Game" button is only visible to the host
if (isHost) ElevatedButton(onPressed: () => _startGame(context), child: Text('Start Game')),
],
),
),
);
},
);
}
}
lib/quiz_screen.dart and leaderboard_screen.dart
The QuizScreen would be another StatefulWidget with a StreamBuilder listening to currentQuestionIndex. It would also have a timer. When the timer hits 0, the host's app updates the currentQuestionIndex in Firestore, and everyone's screen moves to the next question automatically.
The LeaderboardScreen would be shown when gameState becomes finished.
Due to the complexity, providing the full, robust code for QuizScreen with timers and answer logic in this format is difficult. However, the structure would be very similar to LobbyScreen: a StreamBuilder that rebuilds the UI based on gameData.
How to Run the App
-
Host (Desktop):
- Connect your machine and enable desktop support if you haven't (
flutter config --enable-windows-desktop).
- Run the app on your desktop:
flutter run -d windows (or macos, linux).
- Enter your name and click "Create Game." You'll see the Lobby.
-
Player 2 (Mobile):
- Connect a physical phone or start an Android/iOS emulator.
- Run the app on the mobile device:
flutter run.
- Enter your name and the Game ID shown on the host's screen. Click "Join Game."
- You'll see your name appear on the host's screen!
-
Host Starts:
- When the host clicks "Start Game," the
gameState in Firestore changes.
- Both the host and player apps will detect this change via their
StreamBuilder and navigate to the QuizScreen.
This is the fundamental pattern for building real-time multiplayer apps in Flutter with Firebase. You have a central data store (Firestore), and all your clients are just "listening" for changes and updating their UI accordingly.