Add a check for build methods that return context.widget (#25046)

This commit is contained in:
Hans Muller
2018-12-11 08:59:28 -08:00
committed by GitHub
parent 3f1c308e58
commit f8a7abb6b8
2 changed files with 24 additions and 0 deletions

View File

@@ -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;
}());
}

View File

@@ -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<void> 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);
});
}