为什么我不能将 Flutter TextField onChanged 事件值传递给文本?

why i can't pass Flutter TextField onChanged event value to a Text?

我正在按照这个使用有状态小部件的示例进行操作,但我不能运行适当地使用它,从 onChanged 事件中获取值与打印功能一起使用,但是当我尝试将值传递给 Text 时,它不会接受,是因为文本在事件本身之外吗?但它仍然在 statfulwidget 中

这是我的代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello You',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new HelloYou(),
    );
  }
}

class HelloYou extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HelloYouState();
}

class _HelloYouState extends State<HelloYou> {
  @override
  Widget build(BuildContext context) {
    String name = "";

    return Scaffold(
      appBar: AppBar(
        title: Text("HelloYou App !"),
        backgroundColor: Colors.blueAccent,
      ),
      body: Container(
          padding: EdgeInsets.all(15.0),
          child: Column(
            children: <Widget>[
              TextField(
                onChanged: (string) {
                  setState(() {
                    name = string;
                    print('my text is :$name');
                  });
                },
              ),
              Text('my name $name')
            ],
          )),
    );
  }
}

将字符串变量移出构建。当您将它放入构建中时,setState 重新运行构建方法并且您的字符串变量消失了。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello You',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new HelloYou(),
    );
  }
}

class HelloYou extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HelloYouState();
}

class _HelloYouState extends State<HelloYou> {

  String name = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("HelloYou App !"),
        backgroundColor: Colors.blueAccent,
      ),
      body: Container(
          padding: EdgeInsets.all(15.0),
          child: Column(
            children: <Widget>[
              TextField(
                onChanged: (string) {
                  setState(() {
                    name = string;
                    print('my text is :$name');
                  });
                },
              ),
              Text('my name $name')
            ],
          )),
    );
  }
}

注意:以防万一您在使用 StatelessWidget 时遇到问题。 在 StatefulWidget 的情况下,您可以在 State 的构建方法之外声明变量,但是当您使用 StatelessWidget 时,您需要在全局范围内声明它,例如,

import 'package:flutter/material.dart';
String name = ""; //variable declared globally

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello You',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new HelloYou(),
    );
  }
}

class HelloYou extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("HelloYou App !"),
        backgroundColor: Colors.blueAccent,
      ),
      body: Container(
          padding: EdgeInsets.all(15.0),
          child: Column(
            children: <Widget>[
              TextField(
                onChanged: (string) {
                  setState(() {
                    name = string;
                    print('my text is :$name');
                  });
                },
              ),
              Text('my name $name')
            ],
          )),
    );
  }
}

大多数时候我们使用 BLoC 或提供程序包来管理状态,它们会重新创建 StatelessWidgets 而不是更新 StatefulWidget 的状态,这会占用更多内存。