我试图在Flutter中的按钮单击事件上创建一个snackbar,但是出现了异常,称未找到ScaffoldMessenger
小部件。相同的代码在Flutter 示例 中似乎可以正常工作。我是否漏掉了什么?谢谢。
这是我的main.dart文件:
import 'package:flutter/material.dart';
void main() => runApp(MyAppWidget());
class MyAppWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyAppWidget> {
final _inputKey = GlobalKey<FormState>();
final _messangerKey = GlobalKey<ScaffoldMessengerState>();
String inputText = "";
String appendString() {
setState(() {
inputText += inputText;
});
return inputText;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
scaffoldMessengerKey: _messangerKey,
home: Scaffold(
appBar: AppBar(
title: Text("Assignment"),
),
body: Form(
key: _inputKey,
child: Column(
children: [
TextFormField(
validator: (inputString) {
inputText = inputString;
if (inputString.length < 5) {
return 'Please enter a longer string';
}
return null;
},
),
ElevatedButton(
onPressed: () {
if (_inputKey.currentState.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Processing Data')));
}
},
child: Text("Enter"),
),
Text(appendString())
],
),
),
),
);
}
}
我遇到了这个异常
════════ Exception caught by gesture ═══════════════════════════════════════════
The following assertion was thrown while handling a gesture:
No ScaffoldMessenger widget found.
MyAppWidget widgets require a ScaffoldMessenger widget ancestor.
Handler: "onTap"
#4 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:991
#3 _MyAppState.build.<anonymous closure>
package:assignment_1/main.dart:48
#2 ScaffoldMessenger.of
package:flutter/…/material/scaffold.dart:224
#1 debugCheckHasScaffoldMessenger
package:flutter/…/material/debug.dart:153
#0 debugCheckHasScaffoldMessenger.<anonymous closure>
package:flutter/…/material/debug.dart:142
When the exception was thrown, this was the stack
Typically, the ScaffoldMessenger widget is introduced by the MaterialApp at the top of your application widget tree.
renderObject: RenderView#a5074
[root]
The ancestors of this widget were
state: _MyAppState#a2cb9
Restarted application in 691ms.
════════ Exception caught by gesture ═══════════════════════════════════════════
The following assertion was thrown while handling a gesture:
No ScaffoldMessenger widget found.
MyAppWidget widgets require a ScaffoldMessenger widget ancestor.
The specific widget that could not find a ScaffoldMessenger ancestor was: MyAppWidget