[go: nahoru, domu]

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add maybeOf for all the cases where of returns nullable. #114120

Merged
merged 5 commits into from
Oct 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,8 @@ class _ExpansionPanelsDemoState extends State<ExpansionPanelsDemo> {
builder: (BuildContext context) {
return CollapsibleBody(
margin: const EdgeInsets.symmetric(horizontal: 16.0),
onSave: () { Form.of(context)!.save(); close(); },
onCancel: () { Form.of(context)!.reset(); close(); },
onSave: () { Form.of(context).save(); close(); },
onCancel: () { Form.of(context).reset(); close(); },
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: TextFormField(
Expand Down Expand Up @@ -244,8 +244,8 @@ class _ExpansionPanelsDemoState extends State<ExpansionPanelsDemo> {
child: Builder(
builder: (BuildContext context) {
return CollapsibleBody(
onSave: () { Form.of(context)!.save(); close(); },
onCancel: () { Form.of(context)!.reset(); close(); },
onSave: () { Form.of(context).save(); close(); },
onCancel: () { Form.of(context).reset(); close(); },
child: FormField<Location>(
initialValue: item.value,
onSaved: (Location? result) { item.value = result; },
Expand Down Expand Up @@ -298,8 +298,8 @@ class _ExpansionPanelsDemoState extends State<ExpansionPanelsDemo> {
child: Builder(
builder: (BuildContext context) {
return CollapsibleBody(
onSave: () { Form.of(context)!.save(); close(); },
onCancel: () { Form.of(context)!.reset(); close(); },
onSave: () { Form.of(context).save(); close(); },
onCancel: () { Form.of(context).reset(); close(); },
child: FormField<double>(
initialValue: item.value,
onSaved: (double? value) { item.value = value; },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ class _PageSelector extends StatelessWidget {
final List<Icon>? icons;

void _handleArrowButtonPress(BuildContext context, int delta) {
final TabController controller = DefaultTabController.of(context)!;
final TabController controller = DefaultTabController.of(context);
if (!controller.indexIsChanging) {
controller.animateTo((controller.index + delta).clamp(0, icons!.length - 1));
}
}

@override
Widget build(BuildContext context) {
final TabController? controller = DefaultTabController.of(context);
final TabController? controller = DefaultTabController.maybeOf(context);
final Color color = Theme.of(context).colorScheme.secondary;
return SafeArea(
top: false,
Expand Down
4 changes: 2 additions & 2 deletions dev/integration_tests/flutter_gallery/lib/gallery/demo.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class TabbedComponentDemoScaffold extends StatefulWidget {

class _TabbedComponentDemoScaffoldState extends State<TabbedComponentDemoScaffold> {
void _showExampleCode(BuildContext context) {
final String? tag = widget.demos![DefaultTabController.of(context)!.index].exampleCodeTag;
final String? tag = widget.demos![DefaultTabController.of(context).index].exampleCodeTag;
if (tag != null) {
Navigator.push(context, MaterialPageRoute<FullScreenCodeDialog>(
builder: (BuildContext context) => FullScreenCodeDialog(exampleCodeTag: tag)
Expand All @@ -72,7 +72,7 @@ class _TabbedComponentDemoScaffoldState extends State<TabbedComponentDemoScaffol
}

Future<void> _showApiDocumentation(BuildContext context) async {
final String? url = widget.demos![DefaultTabController.of(context)!.index].documentationUrl;
final String? url = widget.demos![DefaultTabController.of(context).index].documentationUrl;
if (url == null) {
return;
}
Expand Down
2 changes: 1 addition & 1 deletion dev/manual_tests/lib/material_arc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ class _AnimationDemoState extends State<AnimationDemo> with TickerProviderStateM
return FloatingActionButton(
child: const Icon(Icons.refresh),
onPressed: () {
_play(_allDemos[DefaultTabController.of(context)!.index]);
_play(_allDemos[DefaultTabController.of(context).index]);
},
);
},
Expand Down
4 changes: 2 additions & 2 deletions dev/manual_tests/lib/overlay_geometry.dart
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,8 @@ class OverlayGeometryAppState extends State<OverlayGeometryApp> {
markers[MarkerType.topLeft] = box!.localToGlobal(Offset.zero);
final Size size = box.size;
markers[MarkerType.bottomRight] = box.localToGlobal(Offset(size.width, size.height));
final ScrollableState? scrollable = Scrollable.of(target.currentContext!);
markersScrollOffset = scrollable!.position.pixels;
final ScrollableState scrollable = Scrollable.of(target.currentContext!);
markersScrollOffset = scrollable.position.pixels;
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class FromSectionExample extends StatelessWidget {
child: Form(
autovalidateMode: AutovalidateMode.always,
onChanged: () {
Form.of(primaryFocus!.context!)?.save();
Form.maybeOf(primaryFocus!.context!)?.save();
},
child: CupertinoFormSection.insetGrouped(
header: const Text('SECTION 1'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class MyStatelessWidget extends StatelessWidget {
// The Builder widget is used to have a different BuildContext to access
// closest DefaultTabController.
child: Builder(builder: (BuildContext context) {
final TabController tabController = DefaultTabController.of(context)!;
final TabController tabController = DefaultTabController.of(context);
tabController.addListener(() {
if (!tabController.indexIsChanging) {
// Your code goes here.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class _MyStatefulWidgetState extends State<MyStatefulWidget> {
child: Form(
autovalidateMode: AutovalidateMode.always,
onChanged: () {
Form.of(primaryFocus!.context!)!.save();
Form.of(primaryFocus!.context!).save();
},
child: Wrap(
children: List<Widget>.generate(5, (int index) {
Expand Down
2 changes: 1 addition & 1 deletion packages/flutter/lib/src/cupertino/page_scaffold.dart
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ class CupertinoPageScaffold extends StatefulWidget {
class _CupertinoPageScaffoldState extends State<CupertinoPageScaffold> {

void _handleStatusBarTap() {
final ScrollController? primaryScrollController = PrimaryScrollController.of(context);
final ScrollController? primaryScrollController = PrimaryScrollController.maybeOf(context);
// Only act on the scroll controller if it has any attached scroll positions.
if (primaryScrollController != null && primaryScrollController.hasClients) {
primaryScrollController.animateTo(
Expand Down
12 changes: 6 additions & 6 deletions packages/flutter/lib/src/material/about.dart
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,7 @@ class _PackagesViewState extends State<_PackagesView> {
}
final String packageName = data.packages[widget.selectedId.value ?? 0];
final List<int> bindings = data.packageLicenseBindings[packageName]!;
_MasterDetailFlow.of(context)!.setInitialDetailPage(
_MasterDetailFlow.of(context).setInitialDetailPage(
_DetailArguments(
packageName,
bindings.map((int i) => data.licenses[i]).toList(growable: false),
Expand Down Expand Up @@ -632,7 +632,7 @@ class _PackagesViewState extends State<_PackagesView> {
numberLicenses: bindings.length,
onTap: () {
widget.selectedId.value = packageIndex;
_MasterDetailFlow.of(context)!.openDetailPage(_DetailArguments(
_MasterDetailFlow.of(context).openDetailPage(_DetailArguments(
packageName,
bindings.map((int i) => data.licenses[i]).toList(growable: false),
));
Expand Down Expand Up @@ -1073,7 +1073,7 @@ class _MasterDetailFlow extends StatefulWidget {
// ```dart
// _MasterDetailFlow.of(context).openDetailPage(arguments);
// ```
static _MasterDetailFlowProxy? of(BuildContext context) {
static _MasterDetailFlowProxy of(BuildContext context) {
_PageOpener? pageOpener = context.findAncestorStateOfType<_MasterDetailScaffoldState>();
pageOpener ??= context.findAncestorStateOfType<_MasterDetailFlowState>();
assert(() {
Expand All @@ -1086,7 +1086,7 @@ class _MasterDetailFlow extends StatefulWidget {
}
return true;
}());
return pageOpener != null ? _MasterDetailFlowProxy._(pageOpener) : null;
return _MasterDetailFlowProxy._(pageOpener!);
}
}

Expand Down Expand Up @@ -1339,13 +1339,13 @@ class _MasterDetailScaffoldState extends State<_MasterDetailScaffold>
@override
void openDetailPage(Object arguments) {
SchedulerBinding.instance.addPostFrameCallback((_) => _detailArguments.value = arguments);
_MasterDetailFlow.of(context)!.openDetailPage(arguments);
_MasterDetailFlow.of(context).openDetailPage(arguments);
}

@override
void setInitialDetailPage(Object arguments) {
SchedulerBinding.instance.addPostFrameCallback((_) => _detailArguments.value = arguments);
_MasterDetailFlow.of(context)!.setInitialDetailPage(arguments);
_MasterDetailFlow.of(context).setInitialDetailPage(arguments);
}

@override
Expand Down
10 changes: 3 additions & 7 deletions packages/flutter/lib/src/material/app_bar.dart
Original file line number Diff line number Diff line change
Expand Up @@ -820,13 +820,9 @@ class _AppBarState extends State<AppBar> {
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_scrollNotificationObserver != null) {
_scrollNotificationObserver!.removeListener(_handleScrollNotification);
}
_scrollNotificationObserver = ScrollNotificationObserver.of(context);
if (_scrollNotificationObserver != null) {
_scrollNotificationObserver!.addListener(_handleScrollNotification);
}
_scrollNotificationObserver?.removeListener(_handleScrollNotification);
_scrollNotificationObserver = ScrollNotificationObserver.maybeOf(context);
_scrollNotificationObserver?.addListener(_handleScrollNotification);
}

@override
Expand Down
4 changes: 2 additions & 2 deletions packages/flutter/lib/src/material/calendar_date_picker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -806,7 +806,7 @@ class _FocusedDate extends InheritedWidget {
return !DateUtils.isSameDay(date, oldWidget.date);
}

static DateTime? of(BuildContext context) {
static DateTime? maybeOf(BuildContext context) {
final _FocusedDate? focusedDate = context.dependOnInheritedWidgetOfExactType<_FocusedDate>();
return focusedDate?.date;
}
Expand Down Expand Up @@ -887,7 +887,7 @@ class _DayPickerState extends State<_DayPicker> {
void didChangeDependencies() {
super.didChangeDependencies();
// Check to see if the focused date is in this month, if so focus it.
final DateTime? focusedDate = _FocusedDate.of(context);
final DateTime? focusedDate = _FocusedDate.maybeOf(context);
if (focusedDate != null && DateUtils.isSameMonth(widget.displayedMonth, focusedDate)) {
_dayFocusNodes[focusedDate.day - 1].requestFocus();
}
Expand Down
7 changes: 3 additions & 4 deletions packages/flutter/lib/src/material/date_picker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1940,12 +1940,11 @@ class _FocusedDate extends InheritedWidget {
return !DateUtils.isSameDay(date, oldWidget.date) || scrollDirection != oldWidget.scrollDirection;
}

static _FocusedDate? of(BuildContext context) {
static _FocusedDate? maybeOf(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<_FocusedDate>();
}
}


class _DayHeaders extends StatelessWidget {
const _DayHeaders();

Expand Down Expand Up @@ -2217,7 +2216,7 @@ class _MonthItemState extends State<_MonthItem> {
void didChangeDependencies() {
super.didChangeDependencies();
// Check to see if the focused date is in this month, if so focus it.
final DateTime? focusedDate = _FocusedDate.of(context)?.date;
final DateTime? focusedDate = _FocusedDate.maybeOf(context)?.date;
if (focusedDate != null && DateUtils.isSameMonth(widget.displayedMonth, focusedDate)) {
_dayFocusNodes[focusedDate.day - 1].requestFocus();
}
Expand All @@ -2237,7 +2236,7 @@ class _MonthItemState extends State<_MonthItem> {

void _dayFocusChanged(bool focused) {
if (focused) {
final TraversalDirection? focusDirection = _FocusedDate.of(context)?.scrollDirection;
final TraversalDirection? focusDirection = _FocusedDate.maybeOf(context)?.scrollDirection;
if (focusDirection != null) {
ScrollPositionAlignmentPolicy policy = ScrollPositionAlignmentPolicy.explicit;
switch (focusDirection) {
Expand Down
4 changes: 2 additions & 2 deletions packages/flutter/lib/src/material/expansion_tile.dart
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ class _ExpansionTileState extends State<ExpansionTile> with SingleTickerProvider
_iconColor = _controller.drive(_iconColorTween.chain(_easeInTween));
_backgroundColor = _controller.drive(_backgroundColorTween.chain(_easeOutTween));

_isExpanded = PageStorage.of(context)?.readState(context) as bool? ?? widget.initiallyExpanded;
_isExpanded = PageStorage.maybeOf(context)?.readState(context) as bool? ?? widget.initiallyExpanded;
if (_isExpanded) {
_controller.value = 1.0;
}
Expand All @@ -359,7 +359,7 @@ class _ExpansionTileState extends State<ExpansionTile> with SingleTickerProvider
});
});
}
PageStorage.of(context)?.writeState(context, _isExpanded);
PageStorage.maybeOf(context)?.writeState(context, _isExpanded);
});
widget.onExpansionChanged?.call(_isExpanded);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/flutter/lib/src/material/ink_decoration.dart
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ class _InkState extends State<Ink> {
_ink = InkDecoration(
decoration: widget.decoration,
configuration: createLocalImageConfiguration(context),
controller: Material.of(context)!,
controller: Material.of(context),
referenceBox: _boxKey.currentContext!.findRenderObject()! as RenderBox,
onRemoved: _handleRemoved,
);
Expand Down
8 changes: 4 additions & 4 deletions packages/flutter/lib/src/material/ink_well.dart
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ class _ParentInkResponseProvider extends InheritedWidget {
@override
bool updateShouldNotify(_ParentInkResponseProvider oldWidget) => state != oldWidget.state;

static _ParentInkResponseState? of(BuildContext context) {
static _ParentInkResponseState? maybeOf(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<_ParentInkResponseProvider>()?.state;
}
}
Expand Down Expand Up @@ -600,7 +600,7 @@ class InkResponse extends StatelessWidget {

@override
Widget build(BuildContext context) {
final _ParentInkResponseState? parentState = _ParentInkResponseProvider.of(context);
final _ParentInkResponseState? parentState = _ParentInkResponseProvider.maybeOf(context);
return _InkResponseStateWidget(
onTap: onTap,
onTapDown: onTapDown,
Expand Down Expand Up @@ -916,7 +916,7 @@ class _InkResponseState extends State<_InkResponseStateWidget>
}
final RenderBox referenceBox = context.findRenderObject()! as RenderBox;
_highlights[type] = InkHighlight(
controller: Material.of(context)!,
controller: Material.of(context),
referenceBox: referenceBox,
color: resolvedOverlayColor,
shape: widget.highlightShape,
Expand Down Expand Up @@ -952,7 +952,7 @@ class _InkResponseState extends State<_InkResponseStateWidget>
}

InteractiveInkFeature _createInkFeature(Offset globalPosition) {
final MaterialInkController inkController = Material.of(context)!;
final MaterialInkController inkController = Material.of(context);
final RenderBox referenceBox = context.findRenderObject()! as RenderBox;
final Offset position = referenceBox.globalToLocal(globalPosition);
final Color color = widget.overlayColor?.resolve(statesController.value) ?? widget.splashColor ?? Theme.of(context).splashColor;
Expand Down
45 changes: 43 additions & 2 deletions packages/flutter/lib/src/material/material.dart
Original file line number Diff line number Diff line change
Expand Up @@ -348,14 +348,55 @@ class Material extends StatefulWidget {
/// Typical usage is as follows:
///
/// ```dart
/// MaterialInkController? inkController = Material.of(context);
/// MaterialInkController? inkController = Material.maybeOf(context);
/// ```
///
/// This method can be expensive (it walks the element tree).
static MaterialInkController? of(BuildContext context) {
///
/// See also:
///
/// * [Material.of], which is similar to this method, but asserts if
/// no [Material] ancestor is found.
static MaterialInkController? maybeOf(BuildContext context) {
return context.findAncestorRenderObjectOfType<_RenderInkFeatures>();
}

/// The ink controller from the closest instance of [Material] that encloses
/// the given context.
///
/// If no [Material] widget ancestor can be found then this method will assert
/// in debug mode, and throw an exception in release mode.
///
/// Typical usage is as follows:
///
/// ```dart
/// MaterialInkController inkController = Material.of(context);
/// ```
///
/// This method can be expensive (it walks the element tree).
///
/// See also:
///
/// * [Material.maybeOf], which is similar to this method, but returns null if
/// no [Material] ancestor is found.
static MaterialInkController of(BuildContext context) {
final MaterialInkController? controller = maybeOf(context);
assert(() {
if (controller == null) {
throw FlutterError(
'Material.of() was called with a context that does not contain a Material widget.\n'
'No Material widget ancestor could be found starting from the context that was passed to '
'Material.of(). This can happen because you are using a widget that looks for a Material '
'ancestor, but no such ancestor exists.\n'
'The context used was:\n'
' $context',
);
}
return true;
}());
return controller!;
}

@override
State<Material> createState() => _MaterialState();

Expand Down
2 changes: 1 addition & 1 deletion packages/flutter/lib/src/material/menu_anchor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ class _MenuAnchorState extends State<MenuAnchor> {
_parent = _MenuAnchorState._maybeOf(context);
_parent?._addChild(this);
_position?.isScrollingNotifier.removeListener(_handleScroll);
_position = Scrollable.of(context)?.position;
_position = Scrollable.maybeOf(context)?.position;
_position?.isScrollingNotifier.addListener(_handleScroll);
final Size newSize = MediaQuery.of(context).size;
if (_viewSize != null && newSize != _viewSize) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ class PaginatedDataTableState extends State<PaginatedDataTable> {
@override
void initState() {
super.initState();
_firstRowIndex = PageStorage.of(context)?.readState(context) as int? ?? widget.initialFirstRowIndex ?? 0;
_firstRowIndex = PageStorage.maybeOf(context)?.readState(context) as int? ?? widget.initialFirstRowIndex ?? 0;
widget.source.addListener(_handleDataSourceChanged);
_handleDataSourceChanged();
}
Expand Down
2 changes: 1 addition & 1 deletion packages/flutter/lib/src/material/scaffold.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2536,7 +2536,7 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, Resto
// top. We implement this by looking up the primary scroll controller and
// scrolling it to the top when tapped.
void _handleStatusBarTap() {
final ScrollController? primaryScrollController = PrimaryScrollController.of(context);
final ScrollController? primaryScrollController = PrimaryScrollController.maybeOf(context);
if (primaryScrollController != null && primaryScrollController.hasClients) {
primaryScrollController.animateTo(
0.0,
Expand Down
Loading