Skip to content

Commit d2e5f21

Browse files
authored
Explain why initState() is too early to depend on an inherited widget (flutter#192727)
When `dependOnInheritedWidgetOfExactType()` is called before `initState()` has completed, the error explains the rule like this: > When an inherited widget changes, for example if the value of Theme.of() changes, its dependent widgets are rebuilt. If the dependent widget's reference to the inherited widget is in a constructor or an initState() method, then the rebuilt dependent widget will not reflect the changes in the inherited widget. That last sentence is easy to read as saying the rebuild itself does not see the change, which is what the issue reports as confusing. The rebuild does see it: a widget that depends on an inherited widget is rebuilt when that inherited widget changes, and a `build()` method that reads it gets the new value. What is never updated is whatever `initState()` read, because the framework calls `initState()` only once for each `State` object and does not call it again for those rebuilds. This replaces that sentence with the actual reason, and adds the same reason to `State.initState`'s documentation, which told readers not to call `dependOnInheritedWidgetOfExactType()` there but not why. The `ErrorHint` that points at `build()` and `didChangeDependencies()` is unchanged. After: > When an inherited widget changes, for example if the value of Theme.of() changes, its dependent widgets are rebuilt. The framework calls initState() only once for each State object and does not call it again for those rebuilds, so a value that initState() reads from an inherited widget is never updated when that inherited widget changes. The existing test for this error (`initState() dependency on Inherited asserts`) only checks that something was thrown, so the message itself was untested; the new test covers it. `ExpectFail` now forwards the caught error so a test can inspect it. The issue also suggests adding a `_StateLifecycle` value between `created` and `initialized`, set just before `initState()` is called. I left that out. A `State` only gets its context after it is constructed (`state._element` is assigned in the `StatefulElement` constructor after `createState()` returns), so the only `State` code that runs with a context before `initState()` completes is `initState()` itself, and a new value would have no constructor case to separate. That is also why the new message no longer mentions constructors; the general advice about constructors stays in the `BuildContext.dependOnInheritedWidgetOfExactType` docs. Fixes flutter#105705 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant in-code documentation (doc comments with `///`). - [x] If this PR introduces a new feature or capability, I created and linked a website documentation issue or PR in [flutter/website] (or verified none is needed). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. If this change needs to override an active code freeze, provide a comment explaining why. The code freeze workflow can be overridden by code reviewers. See pinned issues for any active code freezes with guidance. **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [flutter/website]: https://github.com/flutter/website [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
1 parent dd5c509 commit d2e5f21

2 files changed

Lines changed: 29 additions & 13 deletions

File tree

‎packages/flutter/lib/src/widgets/framework.dart‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -999,9 +999,11 @@ abstract class State<T extends StatefulWidget> with Diagnosticable {
999999
/// {@endtemplate}
10001000
///
10011001
/// You should not use [BuildContext.dependOnInheritedWidgetOfExactType] from this
1002-
/// method. However, [didChangeDependencies] will be called immediately
1003-
/// following this method, and [BuildContext.dependOnInheritedWidgetOfExactType] can
1004-
/// be used there.
1002+
/// method: the framework calls this method only once for each [State] object
1003+
/// and does not call it again when an inherited widget changes, so a value
1004+
/// read here from an inherited widget is never updated. However,
1005+
/// [didChangeDependencies] will be called immediately following this method,
1006+
/// and [BuildContext.dependOnInheritedWidgetOfExactType] can be used there.
10051007
///
10061008
/// Implementations of this method should start with a call to the inherited
10071009
/// method, as in `super.initState()`.
@@ -6075,10 +6077,10 @@ class StatefulElement extends ComponentElement {
60756077
),
60766078
ErrorDescription(
60776079
'When an inherited widget changes, for example if the value of Theme.of() changes, '
6078-
"its dependent widgets are rebuilt. If the dependent widget's reference to "
6079-
'the inherited widget is in a constructor or an initState() method, '
6080-
'then the rebuilt dependent widget will not reflect the changes in the '
6081-
'inherited widget.',
6080+
'its dependent widgets are rebuilt. The framework calls initState() only once for '
6081+
'each State object and does not call it again for those rebuilds, so a value that '
6082+
'initState() reads from an inherited widget is never updated when that inherited '
6083+
'widget changes.',
60826084
),
60836085
ErrorHint(
60846086
'Typically references to inherited widgets should occur in widget build() methods. Alternatively, '

‎packages/flutter/test/widgets/inherited_test.dart‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ class ValueInherited extends InheritedWidget {
3333

3434
class ExpectFail extends StatefulWidget {
3535
const ExpectFail(this.onError, {super.key});
36-
final VoidCallback onError;
36+
final ValueChanged<Object> onError;
3737

3838
@override
3939
ExpectFailState createState() => ExpectFailState();
@@ -46,7 +46,7 @@ class ExpectFailState extends State<ExpectFail> {
4646
try {
4747
context.dependOnInheritedWidgetOfExactType<TestInherited>(); // should fail
4848
} catch (e) {
49-
widget.onError();
49+
widget.onError(e);
5050
}
5151
}
5252

@@ -529,16 +529,30 @@ void main() {
529529

530530
testWidgets('initState() dependency on Inherited asserts', (WidgetTester tester) async {
531531
// This is a regression test for https://github.com/flutter/flutter/issues/5491
532-
var exceptionCaught = false;
532+
// and https://github.com/flutter/flutter/issues/105705.
533+
Object? error;
533534

534535
final parent = TestInherited(
535-
child: ExpectFail(() {
536-
exceptionCaught = true;
536+
child: ExpectFail((Object caughtError) {
537+
error = caughtError;
537538
}),
538539
);
539540
await tester.pumpWidget(parent);
540541

541-
expect(exceptionCaught, isTrue);
542+
expect(error, isFlutterError);
543+
final message = error.toString();
544+
expect(
545+
message,
546+
contains(
547+
'dependOnInheritedWidgetOfExactType<TestInherited>() or dependOnInheritedElement() '
548+
'was called before ExpectFailState.initState() completed',
549+
),
550+
);
551+
// The error should explain that initState() runs only once for each State
552+
// object, so a value it reads from an inherited widget is never updated.
553+
expect(message, contains('calls initState() only once for each State object'));
554+
expect(message, contains('is never updated when that inherited widget changes'));
555+
expect(message, contains('can be placed in the didChangeDependencies method'));
542556
});
543557

544558
testWidgets('InheritedNotifier', (WidgetTester tester) async {

0 commit comments

Comments
 (0)