How can I do this on same page have 2 different widgets? I want to display the content while I'm typing.
It only works if I assign it to a different variable but could I use the controller.text and avoid creating unnecessary variables and applying the SetState?
Widget _price() {
return ListTile(
leading: Icon(Icons.attach_money),
title: TextFormField(
controller: _priceController,
decoration: InputDecoration(hintText: translate('rent.buy_price')),
maxLength: 5,
keyboardType: TextInputType.number,
validator: (value) {
if (value.isEmpty || value == ' ' || value == '') {
return translate('fill_field');
}
return null;
},
onChanged: (String newPrice) {
print(_priceController.text); // I get the correct value
// also tried SetState() here but doesn't work
},
),
);
}
You can use the TextEditingController
's onChanged
function to call setState(() {})
to set the text of the other widget in real-time.
class Thing extends StatefulWidget {
@override
_ThingState createState() => _ThingState();
}
class _ThingState extends State<Thing> {
TextEditingController controller;
@override
void initState() {
controller = TextEditingController();
super.initState();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
controller: controller,
onChanged: (text) => setState(() {}),
),
Text(controller.text),
],
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.