簡體   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,
        )),
  );
}

我創建了這樣一個小部件。 然后我將它添加到我想使用它的地方,如下所示。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM