How can a button disable a TextField, so when I click the button I can't change the TextField's value?
CodePudding user response:
Both TextField
and TextFormField
has a property called enabled
, it's a bool, also you need to add a controller, and this can be achieved controlled by :
bool? enabled;
TextFormField(
enabled:enabled
)
//for the button
GestureDetector(onTap: () {
setState(() {
enabled = false;
});
})
CodePudding user response:
You should change the TextField
enabled property to false when the button is pressed. Here is an example:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: Center(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
@override
_State createState() => _State();
}
class _State extends State<MyStatefulWidget> {
bool isTextFieldEnabled = true;
@override
Widget build(BuildContext context) {
return Container(
child: Column(children: [
TextField(enabled: isTextFieldEnabled,),
ElevatedButton(child: Text('Press Me To Disable TextField'),
onPressed: () {
setState(() {
isTextFieldEnabled = false;
});
},),
],)
);
}
}
CodePudding user response:
you can use enabled false on text field:
TextField(
keyboardType: TextInputType.number,
enabled: false,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Current Miles',
),
),
but if you still want to handle a click on your text field you should use follow:
TextField(
readOnly: true,
enableInteractiveSelection: true,
onTap: () {
do_something(),
},
),
you need to use 'setState' on you button 'onPressed' and put any of the above needed flags in a variable and set accordingly.