【问题标题】:Value of variable altered by Text Field is not updated in Flat Button文本字段更改的变量值未在平面按钮中更新
【发布时间】:2020-11-01 18:22:17
【问题描述】:

这里是构建函数。最初为 null 的变量 newTaskTitle 从 TextField 中获取值。但是这个值不会反映在 Flat Button 小部件中。 newTaskTitle 的值在 FlatButton 小部件中保持为空。帮助我了解我哪里出错了。

Widget build(BuildContext context) {
    String newTaskTitle;

    return Container(
      color: Color(0xFF757575),
      child: Container(
        padding: EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Text(
              'Add Task',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.lightBlueAccent,
                fontSize: 30,
              ),
            ),
            TextField(
              autofocus: true,
              textAlign: TextAlign.center,
              onChanged: (newText) {
                newTaskTitle = newText;
                print(newTaskTitle);
              },
            ),
            SizedBox(
              height: 10,
            ),
            FlatButton(
              padding: EdgeInsets.all(10),
              color: Colors.lightBlueAccent,
              onPressed: () {
                print(newTaskTitle);
                addTaskCallback(newTaskTitle);
              },
              child: Text(
                'Add',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

要克隆项目,部分完成的代码可以在这里找到:https://github.com/vkmanojk/Flutter/tree/master/todoey_flutter

提前致谢。

【问题讨论】:

  • 你有没有尝试在build()方法之外声明,并在onChanged()中调用setState()
  • @MohamedSayed 我试过了。结果还是一样。另外,我使用了StateLess 小部件,因此在方法之外声明变量会引发警告并且setState() 是不可能的。
  • 您是否收到您在控制台中输入的字词?那是你使用 print 的时候吗?
  • @KrishBhanushali 是的。
  • 当输入文本为 hhh - I/flutter (32727): h I/flutter (32727): hh I/flutter (32727): hhh I/flutter (32727): null 为控制台输出

标签: android android-studio flutter flutter-layout flatbutton


【解决方案1】:

嘿 Manoj,我可以看到您使用无状态小部件来执行此任务,并且您在此处声明变量:

Widget build(BuildContext context) {
String newTaskTitle;     <----- Here 

所以我的答案是不要在这里声明它请在你的导入下方像这样在全局 umm 中声明它

import 'material.dart';
String newTaskTitle;   <--- Here or anywhere outside the scope of Stateless widget

现在我们通常更喜欢使用有状态的小部件来完成这样的任务。 希望这有效:)

【讨论】:

  • 谢谢@Krish。这确实解决了问题。但我不明白为什么在构建函数中创建变量不起作用。在最近的更新之前它确实工作得更早。如果您能澄清一下,那将是非常可观的。再次感谢您。
  • 感谢您的赞赏,我会尽快回复您。 :)
猜你喜欢
  • 2019-05-27
  • 1970-01-01
  • 2021-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-03
  • 2020-04-04
相关资源
最近更新 更多