Features
- User guesses a random number.
- Use
while
loops to check if the guess is correct.
Concepts Used
- Control Flow
- Functions
- Random Number Generation
Implementation
- UI: TextField for guessing the number and a button to check.
- Logic: Generate a random number and compare it with the user’s guess.
Final Result
How the App Works
- Generate a Random Number:
- When the app starts,
_targetNumber
is initialized to a random number between 1 and 100.
- When the app starts,
- User Input:
- The user enters their guess in the
TextField
.
- The user enters their guess in the
- Check the Guess:
- The user presses the “Check Guess” button, triggering the
checkGuess
function:- If the guess is invalid, an error message is shown.
- If the guess is too high, the feedback says “Too high!”.
- If the guess is too low, the feedback says “Too low!”.
- If the guess is correct, the feedback says “Congratulations!”.
- The user presses the “Check Guess” button, triggering the
- Feedback Display:
- The result is updated and displayed below the button.
Code
number_guessing_screen.dart
import 'dart:math';
import 'package:flutter/material.dart';
class NumberGuessingApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: NumberGuessingScreen(),
);
}
}
class NumberGuessingScreen extends StatefulWidget {
@override
_NumberGuessingScreenState createState() => _NumberGuessingScreenState();
}
class _NumberGuessingScreenState extends State<NumberGuessingScreen> {
final TextEditingController _controller = TextEditingController();
final int _targetNumber = Random().nextInt(100) + 1; // Random number (1–100)
String _result = '';
void checkGuess() {
final guess = int.tryParse(_controller.text); // Parse user input
if (guess == null) {
setState(() {
_result = 'Please enter a valid number.';
});
return;
}
if (guess > _targetNumber) {
setState(() {
_result = 'Too high! Try again.';
});
} else if (guess < _targetNumber) {
setState(() {
_result = 'Too low! Try again.';
});
} else {
setState(() {
_result = 'Congratulations! You guessed it right!';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Number Guessing Game')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: _controller,
keyboardType: TextInputType.number,
decoration: InputDecoration(labelText: 'Enter your guess (1–100)'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: checkGuess,
child: Text('Check Guess'),
),
SizedBox(height: 20),
Text(
_result,
style: TextStyle(fontSize: 18),
),
],
),
),
);
}
}
main.dart
import 'package:flutter/material.dart';
import 'package:number_guessing_app/number_guessing_screen.dart';
void main() {
runApp(NumberGuessingApp());
}
Code Explanation
1. Code Overview
The app includes:
- A random number generator to generate the target number.
- A TextField for user input.
- A button to check the guess.
- Feedback messages to guide the user toward the correct guess.
Code Breakdown
Main Entry Point
import 'package:flutter/material.dart';
import 'package:number_guessing_app/number_guessing_screen.dart';
void main() {
runApp(NumberGuessingApp());
}
main()
: The entry point of the app.runApp(NumberGuessingApp())
: Launches theNumberGuessingApp
.
NumberGuessingApp Class
class NumberGuessingApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: NumberGuessingScreen(),
);
}
}
MaterialApp
:- Sets up the app with Material Design.
home
: The starting screen is set toNumberGuessingScreen
.
NumberGuessingScreen
This class is a StatefulWidget
because the app requires dynamic updates (feedback messages).
class NumberGuessingScreen extends StatefulWidget {
@override
_NumberGuessingScreenState createState() => _NumberGuessingScreenState();
}
StatefulWidget
: Needed for managing dynamic UI updates.
Random Number Generation
final int _targetNumber = Random().nextInt(100) + 1; // Random number (1–100)
Random().nextInt(100)
: Generates a random number between0
and99
.+ 1
: Shifts the range to1–100
.
User Input Handling
Text Input
final TextEditingController _controller = TextEditingController();
TextEditingController
: Captures the user input from theTextField
.
TextField(
controller: _controller,
keyboardType: TextInputType.number,
decoration: InputDecoration(labelText: 'Enter your guess (1–100)'),
)
- Purpose: Lets the user type their guess.
keyboardType: TextInputType.number
: Restricts the keyboard to numeric input.
Check the Guess
void checkGuess() {
final guess = int.tryParse(_controller.text); // Converts input to an integer
if (guess == null) {
setState(() {
_result = 'Please enter a valid number.';
});
return;
}
if (guess > _targetNumber) {
setState(() {
_result = 'Too high! Try again.';
});
} else if (guess < _targetNumber) {
setState(() {
_result = 'Too low! Try again.';
});
} else {
setState(() {
_result = 'Congratulations! You guessed it right!';
});
}
}
int.tryParse()
: Converts the text input into an integer. Returnsnull
if the input is invalid.- Logic:
- If the guess is
null
, display an error message. - Compare the guess with
_targetNumber
:- If
guess > _targetNumber
: Display “Too high!” - If
guess < _targetNumber
: Display “Too low!” - Otherwise: Display “Congratulations!”
- If
- If the guess is
Result Display
Text(
_result,
style: TextStyle(fontSize: 18),
)
Displays the feedback (_result
) dynamically based on the user’s guess.
Scaffold and Layout
return Scaffold(
appBar: AppBar(title: Text('Number Guessing Game')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(...), // Input field
SizedBox(height: 20),
ElevatedButton(...), // Button to check guess
SizedBox(height: 20),
Text(...), // Feedback result
],
),
),
);
Scaffold
: Provides a basic layout with an app bar and a body.
Column
: Vertically stacks the TextField
, ElevatedButton
, and result Text
.