我正在尝试打电话
Scaffold.of(context).showSnackBar(SnackBar( content: Text("Snack text"), ));
里面onPressed的floatingActionButton支架。
onPressed
floatingActionButton
我得到这个错误
I/flutter (18613): Scaffold.of() called with a context that does not contain a Scaffold. I/flutter (18613): No Scaffold ancestor could be found starting from the context that was passed to ....
当您Scaffold.of(context)在体内调用时,它指向一种解决方案。
Scaffold.of(context)
https://docs.flutter.io/flutter/material/Scaffold/of.html
但是,如果您在onPressed of中调用它,则相同的解决方案将不起作用 FloatingActionButton
FloatingActionButton
更新:第二个解决方案比此解决方案更好。
您应该将floatingActionButton小部件放在构建器小部件中。下面的代码应该工作:
@override Widget build(BuildContext context) { return new Scaffold( floatingActionButton: new Builder(builder: (BuildContext context) { return new FloatingActionButton(onPressed: () { Scaffold .of(context) .showSnackBar(new SnackBar(content: new Text('Hello!'))); }); }), body: new Container( padding: new EdgeInsets.all(32.0), child: new Column( children: <Widget>[ new MySwitch( value: _switchValue, onChanged: (bool value) { if (value != _switchValue) { setState(() { _switchValue = value; }); } }, ) ], ), ), );