Add a check for build methods that return context.widget (#25046)
This commit is contained in:
@@ -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;
|
||||
}());
|
||||
}
|
||||
|
||||
16
packages/flutter/test/widgets/build_fail_test.dart
Normal file
16
packages/flutter/test/widgets/build_fail_test.dart
Normal 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);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user