5
votes

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.

2

2 Answers

2
votes

You can directly pass the screen's width and height as a parameter for the widget ShapesPainter if that is all what you need.

Solution Code:

class ShapesPainter extends CustomPainter {

  final double width;
  final double height;

  ShapesPainter({this.width,this.height});

  @override
  void paint(Canvas canvas, Size size) {

    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;
  }
}

Usage:

// Wherever you'll be using it
ShapesPainter(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
)
0
votes

In the following way, you can get the device screen size without declaring them in the build method.

  void paint(BuildContext context)
{
  double width = MediaQuery.of(context).size.width;
  double height = MediaQuery.of(context).size.height;
}

And you can access them inside other file build methods after importing this method.

paint(context)