I am trying to get screen size in flutter inside a custom class which donot have build method in it. How can i get screen size without using buildcontext class?
The following code :
class ShapesPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
BuildContext context;
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
final paint = Paint();
paint.color = Colors.deepOrange;
var center = Offset(size.width / 2, size.height / 2);
print(height);
print(width);
Rect rect = Rect.fromLTWH(0.0, 0.0, width, height);
canvas.drawRect(rect, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
gives following error :
The following assertion was thrown during paint(): 'package:flutter/src/widgets/media_query.dart': Failed assertion: line 689 pos 12: 'context != null': is not true.
use
MediaQueryData.fromWindow(WidgetsBinding.instance.window);
you can use it to get MediaQuery without need context it depend on instance of window to get size information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With