有什么方法可以在文本字段中捕获按键?在我的情况下,当用户在文本字段内按Enter键时,将存储值。为此,我需要像Kotlin + Android一样使用Keypress-event。由于它有趣且跨平台,所以我本周才开始尝试颤动。
有两种方法可以执行1)。使用像这样的TextField小部件随附的onChanged
方法,
TextField(
onChanged: (text) {
print("First text field: $text");
},
);
2)。使用TextEditingController
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Retrieve Text Input',
home: MyCustomForm(),
);
}
}
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
@override
_MyCustomFormState createState() => _MyCustomFormState();
}
// Define a corresponding State class.
// This class holds data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
// Create a text controller and use it to retrieve the current value
// of the TextField.
final myController = TextEditingController();
@override
void initState() {
super.initState();
myController.addListener(_printLatestValue);
}
@override
void dispose() {
// Clean up the controller when the widget is removed from the widget tree.
// This also removes the _printLatestValue listener.
myController.dispose();
super.dispose();
}
_printLatestValue() {
print("Second text field: ${myController.text}");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Retrieve Text Input'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
TextField(
onChanged: (text) {
print("First text field: $text");
},
),
TextField(
controller: myController,
),
],
),
),
);
}
}
示例取自https://flutter.dev/docs/cookbook/forms/text-field-changes