From ab688b29ac0609c2bec7794ec6b4493ba8f70695 Mon Sep 17 00:00:00 2001 From: Ian Hickson Date: Mon, 31 Oct 2016 22:07:33 -0700 Subject: [PATCH] Make Scaffold.of() more helpful when it can't find a Scaffold (#6612) --- .../flutter/lib/src/material/scaffold.dart | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/flutter/lib/src/material/scaffold.dart b/packages/flutter/lib/src/material/scaffold.dart index 0480b7efa2..6c9f645fe9 100644 --- a/packages/flutter/lib/src/material/scaffold.dart +++ b/packages/flutter/lib/src/material/scaffold.dart @@ -425,7 +425,35 @@ class Scaffold extends StatefulWidget { /// ); /// } /// ``` - static ScaffoldState of(BuildContext context) => context.ancestorStateOfType(const TypeMatcher()); + /// + /// 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()); + 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 ScaffoldState createState() => new ScaffoldState();