在不包含Scaffold的上下文中调用Scaffold.of() [英] Scaffold.of() called with a context that does not contain a Scaffold
问题描述
如您所见,我的按钮在Scaffold的体内.但是我得到了这个例外:
As you can see my button is inside Scaffold's body. But I get this exception:
Scaffold.of().
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SnackBar Playground'),
),
body: Center(
child: RaisedButton(
color: Colors.pink,
textColor: Colors.white,
onPressed: _displaySnackBar(context),
child: Text('Display SnackBar'),
),
),
);
}
}
_displaySnackBar(BuildContext context) {
final snackBar = SnackBar(content: Text('Are you talkin\' to me?'));
Scaffold.of(context).showSnackBar(snackBar);
}
我找到了解决该问题的另一种方法.如果我们为Scaffold提供一个名为GlobalKey的键,则可以如下所示显示SnackBar,而无需使用Builder小部件来包装我们的主体.返回Scaffold的小部件应该是有状态的小部件.:
I found an another solution to this problem. If we give Scaffold a key which is GlobalKey, we can display the SnackBar as following without need to wrap our body with Builder widget. The widget which return Scaffold should be Stateful widget though.:
_scaffoldKey.currentState.showSnackBar(snackbar);
推荐答案
发生此异常是因为您正在使用实例化Scaffold
的窗口小部件的context
.不是Scaffold
子级的context
.
This exception happens because you are using the context
of the widget that instantiated Scaffold
. Not the context
of a child of Scaffold
.
您可以通过使用其他上下文来解决此问题:
You can solve this by just using a different context :
Scaffold(
appBar: AppBar(
title: Text('SnackBar Playground'),
),
body: Builder(
builder: (context) =>
Center(
child: RaisedButton(
color: Colors.pink,
textColor: Colors.white,
onPressed: () => _displaySnackBar(context),
child: Text('Display SnackBar'),
),
),
),
);
请注意,虽然我们在这里使用Builder
,但这并不是获取其他BuildContext
的唯一方法.
Note that while we're using Builder
here, this is not the only way to obtain a different BuildContext
.
还可以将子树提取到其他Widget
中(通常使用extract widget
重构)
It is also possible to extract the subtree into a different Widget
(usually using extract widget
refactor)
这篇关于在不包含Scaffold的上下文中调用Scaffold.of()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!