按下按钮时显示在 TextField() 中键入的文本

Display text typed in TextField() when button pressed

我想在按下 FloatingActionButton 时显示 TextField 中给出的输入,而不是下图中显示为“结果”的文本。

import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: const ScreenHomes(),
    );
  }
}
class ScreenHomes extends StatefulWidget {
  const ScreenHomes({Key? key}) : super(key: key);

  @override
  State<ScreenHomes> createState() => _ScreenHomesState();
}
class _ScreenHomesState extends State<ScreenHomes> {
  @override
  Widget build(BuildContext context) {
    final _textinfield = TextEditingController();
    var newtext = "";
    return Scaffold(
      appBar: AppBar(backgroundColor: Colors.lightBlue),
      body: SafeArea(
          child: Center(
              child: Column(children: [
        Container(
            child: Text(
          newtext,
          style: TextStyle(fontSize: 50),
        )),
        TextField(
          controller: _textinfield,
          decoration: InputDecoration(
              border: OutlineInputBorder(), hintText: "Type to Print"),
        )
      ]))),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.print),
          onPressed: () {
            setState(() {
              newtext = _textinfield.text;
            });
          }),
    );
  }
}

您可以像这样使用 onChanged

TextField(
  onChanged: (txt)=> setState(()=> newtext = txt),
  decoration: InputDecoration(
     border: OutlineInputBorder(), hintText: "Type to Print"),
),

你做的一切都正确只是在构建函数中声明变量的错误

Do not declare var newtext inside the build function.

您必须在构建函数之前声明这两个变量。您的代码发生的事情是,当您调用 setState 函数时,构建函数是 re-run。在 build 函数中,flutter 再次将 newtext 设置为 "" 空字符串。这就是您没有 newtext 的更新值的原因。

Just move the newtext and _textinfield variable before the build function.


class _ScreenHomesState extends State<ScreenHomes> {
   String newtext = "";
   final _textinfield = TextEditingController();
  @override
  Widget build(BuildContext context) {
    // do not initialize variables here 
    // cause every time you rebuild this (call setState) the  variable will be reinitialized
    
    return Scaffold(
      appBar: AppBar(backgroundColor: Colors.lightBlue),
      body: SafeArea(
          child: Center(
              child: Column(children: [
        Container(
            child: Text(
          newtext,
          style: TextStyle(fontSize: 50),
        )),
        TextField(
          controller: _textinfield,
          decoration: InputDecoration(
              border: OutlineInputBorder(), hintText: "Type to Print"),
        )
      ]))),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.print),
          onPressed: () {
            setState(() {
              newtext = _textinfield.text;
            });
          }),
    );
  }
}