From f8a7abb6b844af1aca54e7314c726d725df18c24 Mon Sep 17 00:00:00 2001 From: Hans Muller Date: Tue, 11 Dec 2018 08:59:28 -0800 Subject: [PATCH] Add a check for build methods that return context.widget (#25046) --- packages/flutter/lib/src/widgets/debug.dart | 8 ++++++++ .../flutter/test/widgets/build_fail_test.dart | 16 ++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 packages/flutter/test/widgets/build_fail_test.dart diff --git a/packages/flutter/lib/src/widgets/debug.dart b/packages/flutter/lib/src/widgets/debug.dart index fcbfe080e1..f6facd95ea 100644 --- a/packages/flutter/lib/src/widgets/debug.dart +++ b/packages/flutter/lib/src/widgets/debug.dart @@ -275,6 +275,14 @@ void debugWidgetBuilderValue(Widget widget, Widget built) { 'To return an empty space that takes as little room as possible, return "new Container(width: 0.0, height: 0.0)".' ); } + if (widget == built) { + throw FlutterError( + 'A build function returned context.widget.\n' + 'The offending widget is: $widget\n' + 'Build functions must never return their BuildContext parameter\'s widget or a child that contains "context.widget". ' + 'Doing so introduces a loop in the widget tree that can cause the app to crash.' + ); + } return true; }()); } diff --git a/packages/flutter/test/widgets/build_fail_test.dart b/packages/flutter/test/widgets/build_fail_test.dart new file mode 100644 index 0000000000..ce503e56a8 --- /dev/null +++ b/packages/flutter/test/widgets/build_fail_test.dart @@ -0,0 +1,16 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter/widgets.dart'; + +Future main() async { + testWidgets('Build method that returns context.widget throws FlutterError', (WidgetTester tester) async { + // Regression test for: https://github.com/flutter/flutter/issues/25041 + await tester.pumpWidget( + Builder(builder: (BuildContext context) => context.widget) + ); + expect(tester.takeException(), isFlutterError); + }); +}