Menu
CoddyTech

Cuestionario: Correcto o incorrecto

Parte de la sección Proyectos del Journey de Flutter de Coddy. Lección 11 de 36.

Toca una respuesta y el cuestionario debería indicarte enseguida si acertaste con verde o si te equivocaste con rojo, y mostrar la respuesta correcta en verde en cualquier caso, para que aprendas.

El estado debe recordar qué respuesta tocaste. int? _picked es null hasta que toques una, así que _picked != null significa que ya respondiste. Una vez que lo hayas hecho, los botones dejan de responder: la primera línea de _pick es una condición de protección.

void _pick(int answer) {
  if (_answered) return;
  setState(() {
    _picked = answer;
  });
}

Una pequeña función determina el color de cada botón. null significa «ningún color propio», y el botón conserva el color de su tema:

Color? _colorFor(int answer) {
  if (!_answered) return null;
  if (answer == _question.correct) return Colors.green;
  if (answer == _picked) return Colors.red;
  return null;
}

Ahora los botones necesitan su posición, no solo su texto, así que el bucle cuenta: for (int i = 0; i < question.answers.length; i++) se ejecuta con i como 0, 1, 2 y 3.

challenge icon

Desafío

Difícil

Colorea las respuestas:

  • añade int? _picked, los getters _question y _answered, y los métodos _pick y _colorFor de la teoría
  • recorre las respuestas por posición con for (int i = 0; ...)
  • cada botón llama a _pick(i); su backgroundColor es _colorFor(i), y su texto es blanco cuando tiene un color

Pruébalo tú mismo

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.deepPurple),
      ),
      home: const QuizScreen(),
    );
  }
}

class Question {
  const Question(this.text, this.answers, this.correct);

  final String text;
  final List<String> answers;
  final int correct;
}

const List<Question> questions = [
  Question('Which widget stacks its children from top to bottom?', ['Row', 'Column', 'Stack', 'Wrap'], 1),
  Question('Which language do you write Flutter apps in?', ['Kotlin', 'Swift', 'Dart', 'JavaScript'], 2),
  Question('What does setState do?', ['Rebuilds the widget', 'Saves the app', 'Closes the screen', 'Plays a sound'], 0),
  Question('Which widget shows a list you can scroll?', ['Container', 'SizedBox', 'Padding', 'ListView'], 3),
  Question('Which widget adds space around its child?', ['Padding', 'Center', 'Icon', 'Text'], 0),
];

class QuizScreen extends StatefulWidget {
  const QuizScreen({super.key});

  @override
  State<QuizScreen> createState() => _QuizScreenState();
}

class _QuizScreenState extends State<QuizScreen> {
  int _index = 0;

  @override
  Widget build(BuildContext context) {
    final question = questions[_index];
    final textTheme = Theme.of(context).textTheme;
    return Scaffold(
      appBar: AppBar(title: const Text('Flutter Quiz')),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text(question.text, style: textTheme.headlineSmall),
            const SizedBox(height: 24),
            for (String answer in question.answers)
              Padding(
                padding: const EdgeInsets.only(bottom: 12),
                child: FilledButton.tonal(
                  style: FilledButton.styleFrom(
                    padding: const EdgeInsets.all(16),
                  ),
                  onPressed: () {},
                  child: Text(answer),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Proyectos

Practica por tu cuenta: Compilador de Flutter online