flutter - 使用 .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。
解决方案
推荐阅读
- javascript - 如何使用给定的 ID 快速重定向?
- python - 对特定列中的特定行求和
- c# - 如何将表单数据传递给 ViewModel 属性?
- php - 未捕获的错误:找不到类“MyApp\Chat”
- java - 在 Apache Beam PCollection 中使用 AutoValueSchema 会给出“RuntimeException:Creator 参数 arg0 与模式字段不对应”
- mysql - 简单的 SQL 查询但返回错误的结果
- amazon-web-services - IAM 用户可以自己创建另一个“子”IAM 用户吗?
- kentico - 找不到咖啡和啤酒产品部分的字段
- python - 调整熊猫数据框中的图像
- java - 添加方法java