Edit Text in Flutter

Edit Text in Flutter – Complete Guide

🛠️ Edit Text in Flutter – Complete Guide

Flutter makes it easy to handle user input using built-in widgets like TextField and TextFormField. Whether you're building a form, taking user notes, or editing data, Flutter has you covered.

🔹 1. Basic Editable Text using TextField

This widget is used to get plain text input from the user:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: EditableTextExample(),
    );
  }
}

class EditableTextExample extends StatefulWidget {
  @override
  _EditableTextExampleState createState() => _EditableTextExampleState();
}

class _EditableTextExampleState extends State<EditableTextExample> {
  TextEditingController _controller = TextEditingController();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Edit Text Example')),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                labelText: 'Enter some text',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 20),
            Text('You typed: \${_controller.text}'),
          ],
        ),
      ),
    );
  }
}

🔄 2. Update Text in Real Time

Use the onChanged callback to respond as the user types:

String typedText = "";

TextField(
  onChanged: (value) {
    setState(() {
      typedText = value;
    });
  },
  decoration: InputDecoration(labelText: 'Type here'),
)

✅ 3. Editable Forms with Validation using TextFormField

If you're building a form and want validation, use TextFormField inside a Form widget:

final _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: TextFormField(
    validator: (value) {
      if (value == null || value.isEmpty) {
        return 'Please enter text';
      }
      return null;
    },
  ),
)
📝 Tip: Always dispose controllers in dispose() method to free memory.

📌 Summary

  • Use TextField for simple input.
  • Use TextFormField for forms and validation.
  • Use TextEditingController to read/write values.
  • onChanged helps in live updates.

Start editing text like a pro in Flutter and make your apps more interactive!

Happy coding! 🚀

Post a Comment

0 Comments

Me