Menu
CoddyTech

React to Typing

Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 23 of 34.

A field can tell you each time its text changes. Give it onChanged:, a function that gets the whole text as it is now:

TextField(
  onChanged: (String value) {
    print(value);
  },
)

Type Ada and this prints three times: A, Ad, Ada. The (String value) is a parameter, like the ones in Functions With Parameters: the field calls your function with its text.

To show the text somewhere else on the screen, keep it in the State and change it with setState, the same way a button changes a count:

onChanged: (String value) {
  setState(() {
    _name = value;
  });
},
challenge icon

Challenge

Easy

Make the greeting follow the field: as you type a name, Hello, stranger! becomes Hello, Ada!. Store the text in _name from onChanged.

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 _name = 'stranger';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Greeter')),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              decoration: const InputDecoration(
                labelText: 'Your name',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 24),
            Text('Hello, $_name!', style: const TextStyle(fontSize: 24)),
          ],
        ),
      ),
    );
  }
}
quiz iconTest yourself

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