Part 1 – Loading Quiz Data from Server in Flutter
🔹 Goal
We will fetch quiz questions from a JSON file hosted online and convert them into a list of Dart objects.
🔹 Sample JSON
[
{
"question": "What is the capital of France?",
"options": ["Berlin", "Madrid", "Paris", "Rome"],
"answer": "Paris"
}
]
🔹 Step 1: Add HTTP Package
dependencies:
flutter:
sdk: flutter
http: ^0.13.6
🔹 Step 2: Create Model
class QuizQuestion {
final String question;
final List<String> options;
final String answer;
QuizQuestion({required this.question, required this.options, required this.answer});
factory QuizQuestion.fromJson(Map<String, dynamic> json) {
return QuizQuestion(
question: json['question'],
options: List<String>.from(json['options']),
answer: json['answer'],
);
}
}
🔹 Step 3: Fetch from Server
Future<List<QuizQuestion>> fetchQuestions() async {
final response = await http.get(Uri.parse('https://example.com/questions.json'));
if (response.statusCode == 200) {
final List data = jsonDecode(response.body);
return data.map((e) => QuizQuestion.fromJson(e)).toList();
} else {
throw Exception('Failed to load');
}
}
Next
In Part 2, we’ll display the questions using radio buttons and allow users to select an answer.
0 Comments