简体   繁体   中英

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. 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. I couldn't find whether the widget I gave for return is wrong or something else.

try to use controller in textFormField use 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,
        )),
  );
}

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.

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