如 Scaffold's of method手册中所述,将小吃店显示为动作的输出需要为 Scaffold.of() 创建一个子上下文。
但是我找不到这里描述的这种更“有效的方法”的例子。
更有效的解决方案是将您的构建功能拆分为多个小部件。这引入了一个新的上下文,您可以从中获取 Scaffold。在此解决方案中,您将拥有一个外部小部件,用于创建由新内部小部件的实例填充的 Scaffold,然后在这些内部小部件中您将使用 Scaffold.of。
我想使用这种方法,因为所有递归缩进都很难阅读。我已经尝试使用函数创建表单的提交按钮,甚至尝试扩展 RaisedButton 类(因此Scaffold.of将在文档中指出的新实例化 Widget 中调用)无济于事。
只有当我Builder在Scaffold我的应用程序的主要内容中使用另一个时它才有效。
这有效
class MyForm extends StatefulWidget {
Login({Key key, this.title}) : super(key: key);
final String title;
@override
_MyFormState createState() => new _MyFormState();
}
class _MyFormState extends State<MyForm> {
@override
Widget build(BuildContext context) {
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
return new Scaffold(
body: new Builder(
builder: (BuildContext context) {
return new ListView(
children: <Widget>[
myForm(context, _formKey),
],
);
},
),
);
}
}
class SubmitButton extends RaisedButton {
SubmitButton({
Key key,
this.onPressed,
this.child,
}) : super(key: key, onPressed: onPressed, child: child);
final VoidCallback onPressed;
final Widget child;
@override
Widget build(BuildContext context) {
return super.build(context);
}
}
Widget myForm(
BuildContext context,
GlobalKey<FormState> _formKey) => new Container(
child: new Form(
key: _formKey,
child: new Column(
children: <Widget>[
new TextFormField(
validator: (value) {
if (value.isEmpty) {
return 'Write Something';
}
},
),
new SubmitButton(
onPressed: () {
if (_formKey.currentState.validate()) {
Scaffold.of(context).showSnackBar(
new SnackBar(content: new Text('Processing'))
);
}
},
child: new Text('Submit'),
),
],
),
),
);
Run Code Online (Sandbox Code Playgroud)
如何删除Builder并简化它?我也尝试扩展进一步的RaisedButton build()方法,但陷入了依赖/打字混乱。我找不到这方面的例子。
是的,如果我们返回一个 Scaffold,那么上下文就无法帮助获得小吃店。通过使用 GlobalKey,我们可以实现这一点。请参阅下面的代码。
class ExampleWidget extends StatefulWidget {
@override
_ExampleWidgetState createState() => new _ExampleWidgetState();
}
class _ExampleWidgetState extends State<ExampleWidget> {
GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState();
_showSnackBar() {
_scaffoldKey.currentState.showSnackBar(
new SnackBar(
content: new Text('You have clicked the button'),
duration: new Duration(seconds: 4),
),
);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
key: _scaffoldKey,
body: new Center(
child: new RaisedButton(
onPressed: _showSnackBar(),
child: new Text('Click Me!'),
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1346 次 |
| 最近记录: |