[英]How can I access the text data I defined in the widget in Flutter?
TextFormField textFormField(String text) {
text;
return TextFormField(
textAlign: TextAlign.center,
style: GoogleFonts.montserrat(),
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelStyle: TextStyle(
fontWeight: FontWeight.bold,
)),
);
}
我创建了这样一个小部件。 然后我将它添加到我想使用它的地方,如下所示。
SizedBox(
width: 80,
child: textFormField("Password"),
),
我在 textFormField 中定义了一个字符串值。 然后我在代码内部调用以分配此字符串值并输入字符串值。 FormField 已正确创建,但我无法访问文本。 我找不到我给退货的小部件是错误的还是其他什么。
尝试在 textFormField 中使用控制器使用 TextEditingController
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class Test extends StatefulWidget {
const Test({Key? key}) : super(key: key);
@override
State<Test> createState() => _TestState();
}
class _TestState extends State<Test> {
final textController = TextEditingController(text: "Password");
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: SizedBox(
width: 150,
child: textFormField(textController),
),
),
ElevatedButton(
onPressed: () {
print(textController.text);
},
child: const Text('call'),
),
],
),
);
}
}
TextFormField textFormField(TextEditingController controller) {
return TextFormField(
controller: controller,
textAlign: TextAlign.center,
style: GoogleFonts.montserrat(),
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelStyle: TextStyle(
fontWeight: FontWeight.bold,
)),
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.