在Flutter中没有buildcontext的类中获取屏幕大小 [英] Getting screen size in a class without buildcontext in Flutter

查看:53
本文介绍了在Flutter中没有buildcontext的类中获取屏幕大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

以下代码:

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":不正确.

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.

推荐答案

您可以直接将屏幕的 width height 传递为小部件 ShapesPainter的参数就是您所需要的.

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

解决方案代码:

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,
)

这篇关于在Flutter中没有buildcontext的类中获取屏幕大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆