Commit ab688b29 authored by Ian Hickson's avatar Ian Hickson Committed by GitHub

Make Scaffold.of() more helpful when it can't find a Scaffold (#6612)

parent 5ded244d
...@@ -425,7 +425,35 @@ class Scaffold extends StatefulWidget { ...@@ -425,7 +425,35 @@ class Scaffold extends StatefulWidget {
/// ); /// );
/// } /// }
/// ``` /// ```
static ScaffoldState of(BuildContext context) => context.ancestorStateOfType(const TypeMatcher<ScaffoldState>()); ///
/// If there is no [Scaffold] in scope, then this will throw an exception.
/// To return null if there is no [Scaffold], then pass `nullOk: true`.
static ScaffoldState of(BuildContext context, { bool nullOk: false }) {
assert(nullOk != null);
assert(context != null);
ScaffoldState result = context.ancestorStateOfType(const TypeMatcher<ScaffoldState>());
if (nullOk || result != null)
return result;
throw new FlutterError(
'Scaffold.of() called with a context that does not contain a Scaffold.\n'
'No Scaffold could be found starting from the context that was passed to Scaffold.of(). '
'This usually happens when the context provided is from the same StatefulWidget as that '
'whose build function actually creates the Scaffold widget being sought.\n'
'There are several ways to avoid this problem. The simplest is to use a Builder to get a '
'context that is "under" the Scaffold. For an example of this, please see the '
'documentation for Scaffold.of():\n'
' https://docs.flutter.io/flutter/material/Scaffold/of.html\n'
'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().\n'
'A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, '
'then use the key.currentState property to obtain the ScaffoldState rather than '
'using the Scaffold.of() function.\n'
'The context used was:\n'
' $context'
);
}
@override @override
ScaffoldState createState() => new ScaffoldState(); ScaffoldState createState() => new ScaffoldState();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment