Let’s Flutter Ep 4 — Guess my number— Explanation

Paweł Antonik
2 min readNov 8, 2019

Welcome back!

Before I explain the solution, keep in mind that, this is simplest and not overcomplicated solution. Real app need architecture and tests. But we will get there later.

Previous article

For quick recap, we are creating simple game where user try to guess what is randomized number. User can type number and click the button to confirm. Our app will notify user with one of three messages, congratulation, number is bigger and number is smaller.

class _MyHomePageState extends State<MyHomePage> {
TextEditingController controller = TextEditingController();
int randomNumber = Random().nextInt(100);
String message;

checkAnswer(int answerNumber) {
setState(() {
if (answerNumber == randomNumber) {
message = 'It is $randomNumber, Congratulation!';
} else if (answerNumber < randomNumber) {
message = 'The number is greater!';
} else {
message = 'Try smaller number!';
}
controller.clear();
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Padding(
padding: const EdgeInsets.all(32.0),
child: Column(
children: <Widget>[
Text(
'My number is in rage 0 - 100',
style: TextStyle(fontSize: 20),
),
Padding(
padding: const EdgeInsets.all(50.0),
child: TextField(
controller: controller,
decoration: InputDecoration(hintText: 'Type your guess'),
keyboardType: TextInputType.number,
),
),
Text(
'$message',
style: TextStyle(fontSize: 15),
),
Padding(
padding: const EdgeInsets.all(24.0),
child: RaisedButton(
child: Text('Check'),
onPressed: () {
checkAnswer(int.parse(controller.text));
},
),
)
],
),
),
);
}

@override
void dispose() {
super.dispose();
controller.dispose();
}
}

Congratulation for creating your first app!

Let me know if it was enough challenging or if you have trouble to undestand previous article. Please leave the comment or send me a message and i will explain better the most difficult part.

Also share with us how much of this app, you was able to do by yourself. It will inspire others to greater effort.

See you in next article we will start another project. Get ready it will be more interesting!

--

--