Numbers From a Text Field
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 25 of 34.
A field always holds a String, even when it shows digits: '12' is text, and '12' * 7 is not 84. To calculate with it, turn it into an int:
int.tryParse('12') // 12
int.tryParse('hello') // nullnull means "no value": 'hello' is not a number, so there is none. The type of the result is int?, an int or null. Before you calculate, give it a value to use instead, with ??:
int age = int.tryParse(value) ?? 0;Read a ?? b as "a, or b if a is null". There is also int.parse, without "try", but it stops the app with an error on text that is not a number, and people type all sorts of things.
On a phone, keyboardType: TextInputType.number opens a keyboard of digits, so people rarely type letters at all.
Challenge
Medium- Make the field open the number keyboard.
- In
onChanged, turn the text into anintwithint.tryParse, using0when it is not a number, and keep it in_age. - Show
That is 35 in dog yearsfor an age of 5: the age times 7.
Try it yourself
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,
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String _ageText = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Dog Years')),
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
decoration: const InputDecoration(
labelText: 'Your age',
border: OutlineInputBorder(),
),
onChanged: (String value) {
setState(() {
_ageText = value;
});
},
),
const SizedBox(height: 24),
Text('That is ? in dog years', style: const TextStyle(fontSize: 24)),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Making It Interactive
Practice on your own: Online Flutter compiler