简体   繁体   English

如何访问我在 Flutter 中的小部件中定义的文本数据?

[英]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,
        )),
  );
}

I have created such a widget.我创建了这样一个小部件。 Then I added it where I want to use it as follows.然后我将它添加到我想使用它的地方,如下所示。

SizedBox(
              width: 80,
              child: textFormField("Password"),
            ),

I have defined a String value in textFormField.我在 textFormField 中定义了一个字符串值。 I then called inside the code to assign this String value and entered the String value.然后我在代码内部调用以分配此字符串值并输入字符串值。 FormField is created properly but I can't access text. FormField 已正确创建,但我无法访问文本。 I couldn't find whether the widget I gave for return is wrong or something else.我找不到我给退货的小部件是错误的还是其他什么。

try to use controller in textFormField use TextEditingController尝试在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM