gpt4 book ai didi

flutter - 如何实现 "efficient way"的Scaffold.of()包装

转载 作者:IT王子 更新时间:2023-10-29 06:51:53 25 4
gpt4 key购买 nike

将 snackbar 显示为 Action 的输出需要为 Scaffold.of() 创建一个子上下文,如 Scaffold 的手册中所述 of method .

但我找不到此处描述的这种更“有效方法”的示例。

A more efficient solution is to split your build function into several widgets. This introduces a new context from which you can obtain the Scaffold. In this solution, you would have an outer widget that creates the Scaffold populated by instances of your new inner widgets, and then in these inner widgets you would use Scaffold.of.

我想使用这种方法,因为所有递归缩进都很难阅读。我已经尝试使用函数创建表单的提交按钮,甚至尝试扩展 RaisedButton 类(因此 Scaffold.of 将在文档中指出的新实例化 Widget 中调用)无济于事。

只有当我在我的应用程序的主 Scaffold 中使用另一个 Builder 时它才有效。

这行得通

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'),
),
],
),
),
);

如何删除 Builder 并简化它?我还尝试进一步扩展 RaisedButton build() 方法,但陷入了依赖/输入困惑。我找不到这方面的例子。

最佳答案

是的,如果我们返回一个脚手架,那么该上下文将无助于获取 snackbar 。通过使用 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!'),
),
),
);
}
}

关于flutter - 如何实现 "efficient way"的Scaffold.of()包装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50478016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com