gpt4 book ai didi

flutter - 在 Flutter 中获取没有构建上下文的类中的屏幕大小

转载 作者:行者123 更新时间:2023-12-03 02:42:59 25 4
gpt4 key购买 nike

我试图在没有构建方法的自定义类中获取 flutter 的屏幕大小。如何在不使用 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;
}
}

给出以下错误:

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.

最佳答案

可以直接通过屏幕的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,
)

关于flutter - 在 Flutter 中获取没有构建上下文的类中的屏幕大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57755174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com