在Flutter中没有buildcontext的类中获取屏幕大小

时间:2019-09-02 10:15:20

标签: flutter dart

我正在尝试在没有构建方法的自定义类中使屏幕大小混乱。不使用buildcontext类如何获取屏幕尺寸?

以下代码:

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

出现以下错误:

  

在paint()期间引发了以下断言:   'package:flutter / src / widgets / media_query.dart':断言失败:行   689位置12:“ context!= null”:不正确。

2 个答案:

答案 0 :(得分:0)

通过以下方式,无需在构建方法中声明即可获取设备屏幕尺寸。

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

导入此方法后,您可以在其他文件构建方法中访问它们。

paint(context)

答案 1 :(得分:-1)

如果需要的话,您可以直接将屏幕的widthheight传递为小部件ShapesPainter的参数。

解决方案代码:

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

用法:

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