Can I override MaterialBanner widget to change its height? - flutter

I was dealing with the ScaffoldMessenger.of(context).showMaterialBanner method and it needs a MaterialBanner widget as parameter.
Goal
In my case I need to put an empty MaterialBanner widget but with a custom height (less than default).
In few words override the original MaterialBanner build method.
What I tried
so I thought that I had to extend a StatefulWidget implementing MaterialBanner:
class MiniBanner extends StatefulWidget implements MaterialBanner {
const MiniBanner({Key? key}) : super(key: key);
#override
List<Widget> get actions => [const SizedBox()];
#override
Animation<double>? get animation => null;
#override
Color? get backgroundColor => Colors.amber;
#override
Widget get content => const SizedBox();
#override
TextStyle? get contentTextStyle => null;
#override
double? get elevation => 0;
#override
bool get forceActionsBelow => false;
#override
Widget? get leading => null;
#override
EdgeInsetsGeometry? get leadingPadding => EdgeInsets.zero;
#override
VoidCallback? get onVisible => null;
#override
OverflowBarAlignment get overflowAlignment => OverflowBarAlignment.end;
#override
EdgeInsetsGeometry? get padding => EdgeInsets.zero;
#override
MaterialBanner withAnimation(Animation<double> newAnimation, {Key? fallbackKey}) {
return MaterialBanner(
key: key ?? fallbackKey,
content: content,
contentTextStyle: contentTextStyle,
actions: actions,
elevation: elevation,
leading: leading,
backgroundColor: backgroundColor,
padding: padding,
leadingPadding: leadingPadding,
forceActionsBelow: forceActionsBelow,
overflowAlignment: overflowAlignment,
animation: newAnimation,
onVisible: onVisible,
);
}
#override
State<MiniBanner> createState() => _MiniBannerState();
}
class _MiniBannerState extends State<MiniBanner> {
#override
Widget build(BuildContext context) {
// I want the code to go here to build a smaller MaterialBanner
return Container(
color: widget.backgroundColor,
height: 10,
);
}
}
But my code keep going to the original MaterialBanner method.
Maybe I'm missing some knowledge about extending stateful widgets.

Solved
The main issue was the return type of the "withAnimation" method. It has to be the same type of your custom widget.
So:
class MiniBanner extends StatefulWidget implements MaterialBanner {
const MiniBanner({
Key key,
this.content = const SizedBox(),
this.contentTextStyle,
this.actions = const [SizedBox()],
this.elevation = 0,
this.leading,
this.backgroundColor = Colors.red, //custom default color
this.padding = EdgeInsets.zero,
this.leadingPadding = EdgeInsets.zero,
this.forceActionsBelow = false,
this.overflowAlignment = OverflowBarAlignment.end,
this.animation,
this.onVisible,
}) : assert(elevation == null || elevation >= 0.0),
assert(content != null),
assert(actions != null),
assert(forceActionsBelow != null),
super(key: key);
#override
final List<Widget> actions;
#override
final Animation<double> animation;
#override
final Color backgroundColor;
#override
final Widget content;
#override
final TextStyle contentTextStyle;
#override
final double elevation;
#override
final bool forceActionsBelow;
#override
final Widget leading;
#override
final EdgeInsetsGeometry leadingPadding;
#override
final VoidCallback onVisible;
#override
final OverflowBarAlignment overflowAlignment;
#override
final EdgeInsetsGeometry padding;
#override
MiniBanner withAnimation(Animation<double> newAnimation, {Key fallbackKey}) {
return MiniBanner(
key: key ?? fallbackKey,
content: content,
contentTextStyle: contentTextStyle,
actions: actions,
elevation: elevation,
leading: leading,
backgroundColor: backgroundColor,
padding: padding,
leadingPadding: leadingPadding,
forceActionsBelow: forceActionsBelow,
overflowAlignment: overflowAlignment,
animation: newAnimation,
onVisible: onVisible,
);
}
#override
State<MiniBanner> createState() => MiniBannerState();
}
class MiniBannerState extends State<MiniBanner> {
#override
Widget build(BuildContext context) {
// Now our MiniBanner correctly build this method
return Container(
color: widget.backgroundColor,
height: 10,
);
}
}
Important note
This code is not null sound safety so if you have a Flutter application with null sound safety enabled you have to change some syntax, like adding ? after the nullable properties and so on.
UPDATE
If you want to really emulate the original MaterialBanner with all the animations, you have to copy almost the entire original "build" method.
Then, to custom your widget, you just have to edit the assignment of materialBanner variable, example:
// other parts of code copied from original build method above
Widget materialBanner = Container(
color: widget.backgroundColor,
height: 10,
);
// other parts of code copied from original build method below

Related

Flutter: howto return the codePoint value from an Icon widget?

I want to bypass an Icon Widget to a custom widget and get the Icons codePoint value make some changes and return the new Icon Widget.
class NewCustomWidget extends StatefulWidget {
const NewCustomWidget({
Key? key,
this.mySize,
this.myIcon,
}) : super(key: key);
final double? mySize;
final Icon? myIcon;
#override
_NewCustomWidgetState createState() => _NewCustomWidgetState();
}
class _NewCustomWidgetState extends State<NewCustomWidget> {
#override
Widget build(BuildContext context) {
return Icon(
???? howto bypass the widget.myIcon's codePoint/IconData to the new Icon ????
color: Colors.black,
size: widget.mySize,
);
}
}
I tried to use the widget.myIcon.toString() but I get only the String "widget"
Icon takes IconData. You can do
return Icon(
widget.myIcon?.icon,
color: Colors.black,
size: widget.mySize,
);

If I use StatefulWidget in StatelessWidget, each StatefulWidget perform like Stateless Widget?

I use Widgets Like this (image). How performed they are?
A Stateful widget will perform exactly like a Stateless widget unless you mutate the state using setState method. The only time UI is rebuilt is when your run the setState((){}) method inside the Stateful widget.
Sample setState example from documentation.
class Bird extends StatefulWidget {
const Bird({
Key? key,
this.color = const Color(0xFFFFE306),
this.child,
}) : super(key: key);
final Color color;
final Widget? child;
#override
State<Bird> createState() => _BirdState();
}
class _BirdState extends State<Bird> {
double _size = 1.0;
void grow() {
setState(() { _size += 0.1; });
}
#override
Widget build(BuildContext context) {
return Container(
color: widget.color,
transform: Matrix4.diagonal3Values(_size, _size, 1.0),
child: widget.child,
);
}
}
Reference: Stateful Widgets - LINK
You can try and learn about Stateful widgets in the above documentation link.

Dynamic theme properties in Flutter which can be set in runtime

I would like to create my own theme properties which can be set in runtime dynamically.
I tried to create an extension for the TextTheme which looks like that:
extension CustomTextTheme on TextTheme {
TextStyle get heading => themeMode == ThemeMode.light
? TextStyle(
color: GlobalTheme.defaultLightTheme.textTheme.headline.color,
fontSize: GlobalTheme.defaultLightTheme.textTheme.headline.fontSize,
)
: TextStyle(
color: GlobalTheme.defaultDarkTheme.textTheme.headline.color,
fontSize: GlobalTheme.defaultLightTheme.textTheme.headline.fontSize,
);
}
The question is how I can change the extension properties on runtime dynamically.
What I want to archive with this is, that I can load a "theme config" from the server and set that theme on each device dynamically.
To pass and get values inside the widget tree you need InheritedWidget.
This is a special type of Widgets that just transfer the information between widgets (like Theme delivers ThemeData).
You can not extend ThemeData with new fields as extensions will not trigger updates on Theme.
But you can create your own CustomTheme which will coexist with the original.
class CustomThemeData {
const CustomThemeData(this.heading);
final TextStyle heading;
#override
bool operator ==(Object other) =>
identical(this, other) ||
other is CustomThemeData &&
runtimeType == other.runtimeType &&
heading == other.heading;
#override
int get hashCode => heading.hashCode;
}
Now create an InheritedWidget that wll provide the custom theme data value (via of) and will add a possibility to update the data (via update)
class CustomTheme extends InheritedWidget {
const CustomTheme({
Key? key,
required this.data,
required this.onUpdate,
required Widget child,
}) : super(key: key, child: child);
final CustomThemeData data;
final void Function(CustomThemeData) onUpdate;
static CustomThemeData of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<CustomTheme>()!.data;
}
static void update(BuildContext context, CustomThemeData data) {
context.dependOnInheritedWidgetOfExactType<CustomTheme>()!.onUpdate(data);
}
#override
bool updateShouldNotify(covariant CustomTheme oldWidget) {
return data != oldWidget.data;
}
}
Here is a holder for custom theme
class ThemeSwitcherWidget extends StatefulWidget {
final CustomThemeData initialTheme;
final Widget child;
const ThemeSwitcherWidget({
Key? key,
required this.initialTheme,
required this.child,
}) : super(key: key);
#override
_ThemeSwitcherWidgetState createState() => _ThemeSwitcherWidgetState();
}
class _ThemeSwitcherWidgetState extends State<ThemeSwitcherWidget> {
CustomThemeData? _updatedTheme;
#override
Widget build(BuildContext context) {
return CustomTheme(
data: _updatedTheme ?? widget.initialTheme,
onUpdate: (newData) => setState(() {
_updatedTheme = newData;
}),
child: widget.child,
);
}
}
And here is an example on how to use all this beauty:
void main() {
runApp(
const ThemeSwitcherWidget(
initialTheme: CustomThemeData(TextStyle()),
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'text',
style: CustomTheme.of(context).heading,
),
ElevatedButton(
onPressed: () {
CustomTheme.update(
context,
const CustomThemeData(TextStyle(
color: Colors.red,
fontSize: 44,
)));
},
child: const Text('Change theme')),
],
),
),
),
);
}
}
To make the code less verbose you may use provider which will do all that magic with updates for you.

How to change the value of a member in a custom widget dynamically based on a changing value passed from outside

I am new to flutter.
I was trying to make a custom widget that uses Bézier curve to draw a gooey circle, which changes its position based on the value of the slider.
I have made a gif to show what I was up to.GooeyCircle
The problem is, I need to change the gooey circle's position(progress) based on _sliderValue, but it seems that the progress in the GooeyCircleWidget stays the initial value and never changes whenever the slider goes. I want it to be passed into the widget dynamically, could anyone please help me find out what I should do? Thanks!
GooeyCircleWidget(
progress: _sliderValue,
color: Colors.blue,
),
class GooeyCircleWidget extends StatefulWidget {
Color color;
double progress ;
_GooeyCircleWcoloridgetState createState() => _GooeyCircleWidgetState(
progress: progress,
color:color,
);
GooeyCircleWidget({
#required this.progress,
this.color
});å
}
class _GooeyCircleWidgetState extends State<GooeyCircleWidget>
with SingleTickerProviderStateMixin {
final double progress;
AnimationController controller;
final Color color;
_GooeyCircleWidgetState(
{#required this.progress,
this.color});
#override
void initState() {
super.initState();
controller = AnimationController(vsync: this);
}
#override
Widget build(BuildContext context) {
print(progress);
// TODO: implement build
return CustomPaint(
painter: AnimatedCirclePainter(
progress: progress,
color: color,
),
size: Size(1080, 200),
);
}
}
Don't pass the variables from GooeyCircleWidget into the constructor of _GooeyCircleWidgetState. Instead use widget.
Like so:
class GooeyCircleWidget extends StatefulWidget {
Color color;
double progress ;
#override
_GooeyCircleWidgetState createState() => _GooeyCircleWidgetState();
GooeyCircleWidget({
#required this.progress,
this.color,
});
}
class _GooeyCircleWidgetState extends State<GooeyCircleWidget>
with SingleTickerProviderStateMixin {
AnimationController controller;
#override
void initState() {
super.initState();
controller = AnimationController(vsync: this);
}
#override
Widget build(BuildContext context) {
print(widget.progress);
// TODO: implement build
return CustomPaint(
painter: AnimatedCirclePainter(
progress: widget.progress,
color: widget.color
),
size: Size(1080, 200),
);
}
}

How to get height of a Widget?

I don't understand how LayoutBuilder is used to get the height of a Widget.
I need to display the list of Widgets and get their height so I can compute some special scroll effects. I am developing a package and other developers provide widget (I don't control them). I read that LayoutBuilder can be used to get height.
In very simple case, I tried to wrap Widget in LayoutBuilder.builder and put it in the Stack, but I always get minHeight 0.0, and maxHeight INFINITY. Am I misusing the LayoutBuilder?
EDIT: It seems that LayoutBuilder is a no go. I found the CustomSingleChildLayout which is almost a solution.
I extended that delegate, and I was able to get the height of widget in getPositionForChild(Size size, Size childSize) method. BUT, the first method that is called is Size getSize(BoxConstraints constraints) and as constraints, I get 0 to INFINITY because I'm laying these CustomSingleChildLayouts in a ListView.
My problem is that SingleChildLayoutDelegate getSize operates like it needs to return the height of a view. I don't know the height of a child at that moment. I can only return constraints.smallest (which is 0, the height is 0), or constraints.biggest which is infinity and crashes the app.
In the docs it even says:
...but the size of the parent cannot depend on the size of the child.
And that's a weird limitation.
To get the size/position of a widget on screen, you can use GlobalKey to get its BuildContext to then find the RenderBox of that specific widget, which will contain its global position and rendered size.
Just one thing to be careful of: That context may not exist if the widget is not rendered. Which can cause a problem with ListView as widgets are rendered only if they are potentially visible.
Another problem is that you can't get a widget's RenderBox during build call as the widget hasn't been rendered yet.
But what if I need to get the size during the build! What can I do?
There's one cool widget that can help: Overlay and its OverlayEntry.
They are used to display widgets on top of everything else (similar to stack).
But the coolest thing is that they are on a different build flow; they are built after regular widgets.
That have one super cool implication: OverlayEntry can have a size that depends on widgets of the actual widget tree.
Okay. But don't OverlayEntry requires to be rebuilt manually?
Yes, they do. But there's another thing to be aware of: ScrollController, passed to a Scrollable, is a listenable similar to AnimationController.
Which means you could combine an AnimatedBuilder with a ScrollController, it would have the lovely effect to rebuild your widget automatically on a scroll. Perfect for this situation, right?
Combining everything into an example:
In the following example, you'll see an overlay that follows a widget inside ListView and shares the same height.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final controller = ScrollController();
OverlayEntry sticky;
GlobalKey stickyKey = GlobalKey();
#override
void initState() {
if (sticky != null) {
sticky.remove();
}
sticky = OverlayEntry(
builder: (context) => stickyBuilder(context),
);
SchedulerBinding.instance.addPostFrameCallback((_) {
Overlay.of(context).insert(sticky);
});
super.initState();
}
#override
void dispose() {
sticky.remove();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
controller: controller,
itemBuilder: (context, index) {
if (index == 6) {
return Container(
key: stickyKey,
height: 100.0,
color: Colors.green,
child: const Text("I'm fat"),
);
}
return ListTile(
title: Text(
'Hello $index',
style: const TextStyle(color: Colors.white),
),
);
},
),
);
}
Widget stickyBuilder(BuildContext context) {
return AnimatedBuilder(
animation: controller,
builder: (_,Widget child) {
final keyContext = stickyKey.currentContext;
if (keyContext != null) {
// widget is visible
final box = keyContext.findRenderObject() as RenderBox;
final pos = box.localToGlobal(Offset.zero);
return Positioned(
top: pos.dy + box.size.height,
left: 50.0,
right: 50.0,
height: box.size.height,
child: Material(
child: Container(
alignment: Alignment.center,
color: Colors.purple,
child: const Text("^ Nah I think you're okay"),
),
),
);
}
return Container();
},
);
}
}
Note:
When navigating to a different screen, call following otherwise sticky would stay visible.
sticky.remove();
This is (I think) the most straightforward way to do this.
Copy-paste the following into your project.
UPDATE: using RenderProxyBox results in a slightly more correct implementation, because it's called on every rebuild of the child and its descendants, which is not always the case for the top-level build() method.
NOTE: This is not exactly an efficient way to do this, as pointed by Hixie here. But it is the easiest.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
typedef void OnWidgetSizeChange(Size size);
class MeasureSizeRenderObject extends RenderProxyBox {
Size? oldSize;
OnWidgetSizeChange onChange;
MeasureSizeRenderObject(this.onChange);
#override
void performLayout() {
super.performLayout();
Size newSize = child!.size;
if (oldSize == newSize) return;
oldSize = newSize;
WidgetsBinding.instance!.addPostFrameCallback((_) {
onChange(newSize);
});
}
}
class MeasureSize extends SingleChildRenderObjectWidget {
final OnWidgetSizeChange onChange;
const MeasureSize({
Key? key,
required this.onChange,
required Widget child,
}) : super(key: key, child: child);
#override
RenderObject createRenderObject(BuildContext context) {
return MeasureSizeRenderObject(onChange);
}
#override
void updateRenderObject(
BuildContext context, covariant MeasureSizeRenderObject renderObject) {
renderObject.onChange = onChange;
}
}
Then, simply wrap the widget whose size you would like to measure with MeasureSize.
var myChildSize = Size.zero;
Widget build(BuildContext context) {
return ...(
child: MeasureSize(
onChange: (size) {
setState(() {
myChildSize = size;
});
},
child: ...
),
);
}
So yes, the size of the parent cannot can depend on the size of the child if you try hard enough.
Personal anecdote - This is handy for restricting the size of widgets like Align, which likes to take up an absurd amount of space.
Here's a sample on how you can use LayoutBuilder to determine the widget's size.
Since LayoutBuilder widget is able to determine its parent widget's constraints, one of its use case is to be able to have its child widgets adapt to their parent's dimensions.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var dimension = 40.0;
increaseWidgetSize() {
setState(() {
dimension += 20;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(children: <Widget>[
Text('Dimension: $dimension'),
Container(
color: Colors.teal,
alignment: Alignment.center,
height: dimension,
width: dimension,
// LayoutBuilder inherits its parent widget's dimension. In this case, the Container in teal
child: LayoutBuilder(builder: (context, constraints) {
debugPrint('Max height: ${constraints.maxHeight}, max width: ${constraints.maxWidth}');
return Container(); // create function here to adapt to the parent widget's constraints
}),
),
]),
),
floatingActionButton: FloatingActionButton(
onPressed: increaseWidgetSize,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Demo
Logs
I/flutter (26712): Max height: 40.0, max width: 40.0
I/flutter (26712): Max height: 60.0, max width: 60.0
I/flutter (26712): Max height: 80.0, max width: 80.0
I/flutter (26712): Max height: 100.0, max width: 100.0
Update: You can also use MediaQuery to achieve similar function.
#override
Widget build(BuildContext context) {
var screenSize = MediaQuery.of(context).size ;
if (screenSize.width > layoutSize){
return Widget();
} else {
return Widget(); /// Widget if doesn't match the size
}
}
Let me give you a widget for that
class SizeProviderWidget extends StatefulWidget {
final Widget child;
final Function(Size) onChildSize;
const SizeProviderWidget(
{Key? key, required this.onChildSize, required this.child})
: super(key: key);
#override
_SizeProviderWidgetState createState() => _SizeProviderWidgetState();
}
class _SizeProviderWidgetState extends State<SizeProviderWidget> {
#override
void initState() {
///add size listener for first build
_onResize();
super.initState();
}
void _onResize() {
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
if (context.size is Size) {
widget.onChildSize(context.size!);
}
});
}
#override
Widget build(BuildContext context) {
///add size listener for every build uncomment the fallowing
///_onResize();
return widget.child;
}
}
EDIT
Just wrap the SizeProviderWidget with OrientationBuilder to make it respect the orientation of the device
I made this widget as a simple stateless solution:
class ChildSizeNotifier extends StatelessWidget {
final ValueNotifier<Size> notifier = ValueNotifier(const Size(0, 0));
final Widget Function(BuildContext context, Size size, Widget child) builder;
final Widget child;
ChildSizeNotifier({
Key key,
#required this.builder,
this.child,
}) : super(key: key) {}
#override
Widget build(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) {
notifier.value = (context.findRenderObject() as RenderBox).size;
},
);
return ValueListenableBuilder(
valueListenable: notifier,
builder: builder,
child: child,
);
}
}
Use it like this
ChildSizeNotifier(
builder: (context, size, child) {
// size is the size of the text
return Text(size.height > 50 ? 'big' : 'small');
},
)
If I understand correctly, you want to measure the dimension of some arbitrary widgets, and you can wrap those widgets with another widget. In that case, the method in the this answer should work for you.
Basically the solution is to bind a callback in the widget lifecycle, which will be called after the first frame is rendered, from there you can access context.size. The catch is that you have to wrap the widget you want to measure within a stateful widget. And, if you absolutely need the size within build() then you can only access it in the second render (it's only available after the first render).
findRenderObject() returns the RenderBox which is used to give the size of the drawn widget and it should be called after the widget tree is built, so it must be used with some callback mechanism or addPostFrameCallback() callbacks.
class SizeWidget extends StatefulWidget {
#override
_SizeWidgetState createState() => _SizeWidgetState();
}
class _SizeWidgetState extends State<SizeWidget> {
final GlobalKey _textKey = GlobalKey();
Size textSize;
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => getSizeAndPosition());
}
getSizeAndPosition() {
RenderBox _cardBox = _textKey.currentContext.findRenderObject();
textSize = _cardBox.size;
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Size Position"),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
"Currern Size of Text",
key: _textKey,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
),
SizedBox(
height: 20,
),
Text(
"Size - $textSize",
textAlign: TextAlign.center,
),
],
),
);
}
}
Output:
There is no direct way to calculate the size of the widget, so to find that we have to take the help of the context of the widget.
Calling context.size returns us the Size object, which contains the height and width of the widget. context.size calculates the render box of a widget and returns the size.
Checkout https://medium.com/flutterworld/flutter-how-to-get-the-height-of-the-widget-be4892abb1a2
In cases where you don't want to wait for a frame to get the size, but want to know it before including it in your tree:
The simplest way is to follow the example of the BuildOwner documentation.
With the following you can just do
final size = MeasureUtil.measureWidget(MyWidgetTree());
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
/// Small utility to measure a widget before actually putting it on screen.
///
/// This can be helpful e.g. for positioning context menus based on the size they will take up.
///
/// NOTE: Use sparingly, since this takes a complete layout and sizing pass for the subtree you
/// want to measure.
///
/// Compare https://api.flutter.dev/flutter/widgets/BuildOwner-class.html
class MeasureUtil {
static Size measureWidget(Widget widget, [BoxConstraints constraints = const BoxConstraints()]) {
final PipelineOwner pipelineOwner = PipelineOwner();
final _MeasurementView rootView = pipelineOwner.rootNode = _MeasurementView(constraints);
final BuildOwner buildOwner = BuildOwner(focusManager: FocusManager());
final RenderObjectToWidgetElement<RenderBox> element = RenderObjectToWidgetAdapter<RenderBox>(
container: rootView,
debugShortDescription: '[root]',
child: widget,
).attachToRenderTree(buildOwner);
try {
rootView.scheduleInitialLayout();
pipelineOwner.flushLayout();
return rootView.size;
} finally {
// Clean up.
element.update(RenderObjectToWidgetAdapter<RenderBox>(container: rootView));
buildOwner.finalizeTree();
}
}
}
class _MeasurementView extends RenderBox with RenderObjectWithChildMixin<RenderBox> {
final BoxConstraints boxConstraints;
_MeasurementView(this.boxConstraints);
#override
void performLayout() {
assert(child != null);
child!.layout(boxConstraints, parentUsesSize: true);
size = child!.size;
}
#override
void debugAssertDoesMeetConstraints() => true;
}
This creates an entirely new render tree separate from the main one, and wont be shown on your screen.
So for example
print(
MeasureUtil.measureWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Row(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.abc),
SizedBox(
width: 100,
),
Text("Moin Meister")
],
),
),
),
);
Would give you Size(210.0, 24.0)
Might be this could help
Tested on Flutter: 2.2.3
Copy Below code this in your project.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
class WidgetSize extends StatefulWidget {
final Widget child;
final Function onChange;
const WidgetSize({
Key? key,
required this.onChange,
required this.child,
}) : super(key: key);
#override
_WidgetSizeState createState() => _WidgetSizeState();
}
class _WidgetSizeState extends State<WidgetSize> {
#override
Widget build(BuildContext context) {
SchedulerBinding.instance!.addPostFrameCallback(postFrameCallback);
return Container(
key: widgetKey,
child: widget.child,
);
}
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);
}
}
declare a variable to store Size
Size mySize = Size.zero;
Add following code to get the size:
child: WidgetSize(
onChange: (Size mapSize) {
setState(() {
mySize = mapSize;
print("mySize:" + mySize.toString());
});
},
child: ()
This is Remi's answer with null safety, since the edit queue is full, I have to post it here.
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
MyHomePageState createState() => MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> {
final controller = ScrollController();
OverlayEntry? sticky;
GlobalKey stickyKey = GlobalKey();
#override
void initState() {
sticky?.remove();
sticky = OverlayEntry(
builder: (context) => stickyBuilder(context),
);
SchedulerBinding.instance
.addPostFrameCallback((_) => Overlay.of(context)?.insert(sticky!));
super.initState();
}
#override
void dispose() {
sticky?.remove();
super.dispose();
}
#override
Widget build(BuildContext context) => Scaffold(
body: ListView.builder(
controller: controller,
itemBuilder: (context, index) {
if (index == 6) {
return Container(
key: stickyKey,
height: 100.0,
color: Colors.green,
child: const Text("I'm fat"),
);
}
return ListTile(
title: Text(
'Hello $index',
style: const TextStyle(color: Colors.white),
),
);
},
),
);
Widget stickyBuilder(BuildContext context) => AnimatedBuilder(
animation: controller,
builder: (_, Widget? child) {
final keyContext = stickyKey.currentContext;
if (keyContext != null) {
final box = keyContext.findRenderObject() as RenderBox;
final pos = box.localToGlobal(Offset.zero);
return Positioned(
top: pos.dy + box.size.height,
left: 50.0,
right: 50.0,
height: box.size.height,
child: Material(
child: Container(
alignment: Alignment.center,
color: Colors.purple,
child: const Text("Nah I think you're okay"),
),
),
);
}
return Container();
},
);
}
use the package: z_tools.
The steps:
1. change main file
void main() async {
runZoned(
() => runApp(
CalculateWidgetAppContainer(
child: Center(
child: LocalizedApp(delegate, MyApp()),
),
),
),
onError: (Object obj, StackTrace stack) {
print('global exception: obj = $obj;\nstack = $stack');
},
);
}
2. use in function
_Cell(
title: 'cal: Column-min',
callback: () async {
Widget widget1 = Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 100,
height: 30,
color: Colors.blue,
),
Container(
height: 20.0,
width: 30,
),
Text('111'),
],
);
// size = Size(100.0, 66.0)
print('size = ${await getWidgetSize(widget1)}');
},
),
The easiest way is to use MeasuredSize it's a widget that calculates the size of it's child in runtime.
You can use it like so:
MeasuredSize(
onChange: (Size size) {
setState(() {
print(size);
});
},
child: Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
);
You can find it here: https://pub.dev/packages/measured_size
It's easy and still can be done in StatelessWidget.
class ColumnHeightWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
final scrollController = ScrollController();
final columnKey = GlobalKey();
_scrollToCurrentProgress(columnKey, scrollController);
return Scaffold(
body: SingleChildScrollView(
controller: scrollController,
child: Column(
children: [],
),
),
);
}
void _scrollToCurrentProgress(GlobalKey<State<StatefulWidget>> columnKey,
ScrollController scrollController) {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
final RenderBox renderBoxRed =
columnKey.currentContext.findRenderObject();
final height = renderBoxRed.size.height;
scrollController.animateTo(percentOfHeightYouWantToScroll * height,
duration: Duration(seconds: 1), curve: Curves.decelerate);
});
}
}
in the same manner you can calculate any widget child height and scroll to that position.
**Credit to #Manuputty**
class OrigChildWH extends StatelessWidget {
final Widget Function(BuildContext context, Size size, Widget? child) builder;
final Widget? child;
const XRChildWH({
Key? key,
required this.builder,
this.child,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return OrientationBuilder(builder: (context, orientation) {
return ChildSizeNotifier(builder: builder);
});
}
}
class ChildSizeNotifier extends StatelessWidget {
final ValueNotifier<Size> notifier = ValueNotifier(const Size(0, 0));
final Widget Function(BuildContext context, Size size, Widget? child) builder;
final Widget? child;
ChildSizeNotifier({
Key? key,
required this.builder,
this.child,
}) : super(key: key);
#override
Widget build(BuildContext context) {
WidgetsBinding.instance!.addPostFrameCallback(
(_) {
notifier.value = (context.findRenderObject() as RenderBox).size;
},
);
return ValueListenableBuilder(
valueListenable: notifier,
builder: builder,
child: child,
);
}
}
**Simple to use:**
OrigChildWH(
builder: (context, size, child) {
//Your child here: mine:: Container()
return Container()
})