Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting screen size in a class without buildcontext in Flutter

Tags:

flutter

dart

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.

like image 481
Manish Wagle Avatar asked Sep 02 '19 10:09

Manish Wagle


1 Answers

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

like image 87
kareem alkoul Avatar answered Sep 20 '22 23:09

kareem alkoul