I'am trying to get the size of an image when it is loaded and widget is already rendered.
So, if call _getSizes()
function in initState
it returns width: 0.0, height: 0.0
.
The same result when I call _getSizes()
in frameBuilder
.
For now I can get desired result from _getSizes()
function if I click floatingActionButton
or use Future.delayed
at least with 500 millisecond delay only, and then it prints the actual container size: width: 375.0, height: 210.9375
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({ Key? key }) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final GlobalKey _imgKey = GlobalKey();
_getSizes() {
final RenderBox renderBox = _imgKey.currentContext!.findRenderObject() as RenderBox;
final boxSize = renderBox.size;
print("width: ${boxSize.width}, height: ${boxSize.height}");
}
@override
void initState() {
super.initState();
WidgetsBinding.instance!.addPostFrameCallback((_) {
print("WidgetsBinding");
_getSizes();
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test Image Load',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Image Asset Load'),
),
body: Center(
child: Container(
key: _imgKey,
child: Image.asset(
'assets/images/landscape_big.jpg',
frameBuilder: (BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded) {
if (wasSynchronouslyLoaded) {
print('wasSynchronouslyLoaded');
}
if (frame != null) {
_getSizes();
}
return child;
}
),
)
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_getSizes();
},
child: const Icon(Icons.update),
backgroundColor: Colors.green,
),
)
);
}
}
How to get the actual size when image asset is loaded and parent container is rendered? Is there any onLoad
method or maybe controller for Image.assets
widget?