首页 > 解决方案 > 使用 .text getter/setter 时 TextEditingController 抛出 null

问题描述

在 Flutter 中,当我为 TextField 分配一个值或使用 TextEditingController 检查 TextField 小部件的值时,我得到一个 NoMethodError ,它说 The getter/setter "text" was called on a null。

我已经使用以下代码尝试了 Widget 测试:

class TestTEC extends StatefulWidget {
  @override
  TestTECstate createState() => TestTECstate();
}

class TestTECstate extends State<TestTEC> {
  var textController = new TextEditingController();
  Widget build(context) {
    return Scaffold(
      body: Row(
        children: <Widget>[
          TextField(controller: textController),
          RaisedButton(onPressed: () {
            setState(() {
              textController.text = "New text";
            });
          }),
        ],
      ),
    );
  }
}

这是我使用的测试代码:

 testWidgets('smoke test', (WidgetTester tester) async {
    // Build our app and trigger a frame.
    await tester.pumpWidget((TestTEC()));
    await tester.tap(find.byType(RaisedButton));
    await tester.pump();
    expect(find.text('New text'), findsOneWidget);
    await tester.enterText(find.byType(TextField), 'I am a text');
    await tester.pump();
    expect(find.text('I am a test'), findsOneWidget);
    await tester.tap(find.byType(RaisedButton));
    await tester.pump();
    expect(find.text('New text'), findsOneWidget);
  });

这是输出:

 NoSuchMethodError: The setter 'text=' was called on null.
  Receiver: null
  Tried calling: text="key"
  dart:core               Object.noSuchMethod
  widget_test.dart 91:11  textEditingControllerTest
  widget_test.dart 75:14  main.<fn>.<fn>

我试过删除并重新安装flutter sdk。同样的问题发生在我的另一台电脑上。

我以前使用过 .text 属性,这个问题在我的版本 1.5.4.hotfix2 之前没有发生过。如果我做错了什么,请纠正我。我什至无法通过controller.text.isEmpty检查TextField是否为空,它还会抛出“text”被调用为null。

标签: flutter

解决方案


推荐阅读