Skip to content

Instantly share code, notes, and snippets.

@Lzyct
Created September 17, 2020 12:45
Show Gist options
  • Select an option

  • Save Lzyct/7d053e4e7d697690225416f0626f9df0 to your computer and use it in GitHub Desktop.

Select an option

Save Lzyct/7d053e4e7d697690225416f0626f9df0 to your computer and use it in GitHub Desktop.
Get Measure SIze of Widget in Flutter
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
typedef void OnWidgetSizeChange(Size size);
class MeasureSize extends StatefulWidget {
final Widget child;
final OnWidgetSizeChange onChange;
const MeasureSize({
Key key,
@required this.onChange,
@required this.child,
}) : super(key: key);
@override
_MeasureSizeState createState() => _MeasureSizeState();
}
class _MeasureSizeState extends State<MeasureSize> {
var widgetKey = GlobalKey();
var oldSize;
void postFrameCallback(_) {
var context = widgetKey.currentContext;
if (context == null) return;
var newSize = context.size;
if (oldSize == newSize) return;
oldSize = newSize;
widget.onChange(newSize);
}
@override
Widget build(BuildContext context) {
SchedulerBinding.instance.addPostFrameCallback(postFrameCallback);
return Container(
key: widgetKey,
child: widget.child,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment