How to Make TextField Read Only in Flutter

I already have a blog post on how to disable Flutter TextField. In this tutorial, let’s learn how to make TextField read-only in Flutter.

You might be thinking what’s the difference between disabling and making read-only. When TextField made read-only you cannot change the text but you can select the text. The property readOnly helps you in this case.

TextField (
         readOnly: true
           )

Following is the complete example.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter TextField Read Only',
      home: FlutterExample(),
    );
  }
}

class FlutterExample extends StatefulWidget {
  @override
  _FlutterExampleState createState() => _FlutterExampleState();
}

class _FlutterExampleState extends State<FlutterExample> {
  final myController = TextEditingController();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Read Only TextField'),
        ),
        body: Padding(
          padding: EdgeInsets.all(16),
          child: Center(
            child: TextField(
              decoration: InputDecoration(
                border: OutlineInputBorder(),
              ),
              readOnly: true,
              controller: myController..text = 'Default Value',
            ),
          ),
        ));
  }
}

And following is the output.

That’s how you make TextField read only in Flutter.

Leave a Comment

Your email address will not be published. Required fields are marked *