didChangeMetrics method

  1. @override
void didChangeMetrics()
override

Called when the application's dimensions change. For example, when a phone is rotated.

This method exposes notifications from dart:ui.PlatformDispatcher.onMetricsChanged.

{@tool snippet}

This StatefulWidget implements the parts of the State and WidgetsBindingObserver protocols necessary to react when the device is rotated (or otherwise changes dimensions).

class MetricsReactor extends StatefulWidget {
  const MetricsReactor({ super.key });

  @override
  State<MetricsReactor> createState() => _MetricsReactorState();
}

class _MetricsReactorState extends State<MetricsReactor> with WidgetsBindingObserver {
  late Size _lastSize;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // [View.of] exposes the view from `WidgetsBinding.instance.platformDispatcher.views`
    // into which this widget is drawn.
    _lastSize = View.of(context).physicalSize;
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    setState(() { _lastSize = View.of(context).physicalSize; });
  }

  @override
  Widget build(BuildContext context) {
    return Text('Current size: $_lastSize');
  }
}

{@end-tool}

In general, this is unnecessary as the layout system takes care of automatically recomputing the application geometry when the application size changes.

See also:

Implementation

@override
void didChangeMetrics() {
  super.didChangeMetrics();
  WidgetsBinding.instance.addPostFrameCallback((_) {
    if (!mounted) return; // 确保在回调执行时组件仍然挂载
    if (isPagePause) return;
    var queryData = MediaQuery.maybeOf(context);
    if (queryData == null) return;
    if (queryData.viewInsets.bottom == 0 && _keyboardShow) {
      //关闭键盘
      _keyboardShow = false;
      onKeyboardHide();
    } else if (queryData.viewInsets.bottom > 0 && !_keyboardShow) {
      //显示键盘
      _keyboardShow = true;
      onKeyboardShow();
    }
  });
}