Menu
CoddyTech

Read a Field With a Controller

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

onChanged hears every letter. Often you only want the text when a button is pressed, like Add or Send. For that, give the field a controller:

final TextEditingController _controller = TextEditingController();

TextField(controller: _controller)

The controller lives in the State, next to your other variables. It is final because it is always the same controller; only the text inside it changes. _controller.text is what the field holds right now, and _controller.clear() empties it.

void _send() {
  print(_controller.text);
  _controller.clear();
}

A controller should be thrown away when its screen is. That is what dispose is for: Flutter calls it when the State goes away.

@override
void dispose() {
  _controller.dispose();
  super.dispose();
}
challenge icon

Challenge

Medium
  • Add a final TextEditingController _controller to the State and give it to the field with controller:.
  • Make _add show the field's text as Last added: Buy milk, then empty the field.
  • Add the dispose method from the theory.

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 _last = 'nothing';

  void _add() {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Tasks')),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              decoration: const InputDecoration(
                labelText: 'New task',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            ElevatedButton(onPressed: _add, child: const Text('Add')),
            const SizedBox(height: 24),
            Text('Last added: $_last', style: const TextStyle(fontSize: 20)),
          ],
        ),
      ),
    );
  }
}
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