如何获取安全区域的大小?

huangapple go评论52阅读模式
英文:

How to get the size of a safe area?

问题

要在Flutter中获取安全区域的大小,您可以使用**'MediaQuery'**类。以下是如何获取安全区域大小的示例代码:

class SafeAreaExample extends StatelessWidget {
  const SafeAreaExample({super.key});

  @override
  Widget build(BuildContext context) {
    double safePadding = MediaQuery.of(context).padding.top;
    return const Placeholder();
  }
}

我尝试在顶部添加填充,但是发现这个填充在某些设备上不起作用,所以我尝试寻找一些解决方案。

英文:

To get the safe area size in flutter, you can use the 'MediaQuery' class. Here an example of how to get the size of safe area.

class SafeAreaExample extends StatelessWidget {
  const SafeAreaExample({super.key});

  @override
  Widget build(BuildContext context) {
    double safePadding = MediaQuery.of(context).padding.top;
    return const Placeholder();
  }
}

I tried to add pandding on top but, that padding is not working in all device than i try to find some solution.

答案1

得分: 1

可以使用MediaQuery.paddingOf(context)轻松实现,如下所示:

@override
Widget build(BuildContext context) {
  double safePadding = MediaQuery.paddingOf(context).top; // 使用这个来获取顶部的内边距
  return const Placeholder();
}

您应该使用SafeArea小部件而不是添加顶部内边距。默认情况下,此小部件还会在底部、左侧和右侧添加内边距。您可以通过添加bottomleftright参数来移除它们。

class SafeAreaExample extends StatelessWidget {
  const SafeAreaExample({super.key});

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      left: false,
      right: false,
      bottom: false,
      child: // 在此处添加您的小部件
    );
  }
}
英文:

It can be done easily by using MediaQuery.paddingOf(context) like this

@override
Widget build(BuildContext context) {
  double safePadding = MediaQuery.paddingOf(context).top; // using this to get padding
  return const Placeholder();
}

You shoud use SafeArea widget instead of add top padding. In default, this widget also add padding on bottom, left and right. You can remove its by adding parameters bottom, left and right.

class SafeAreaExample extends StatelessWidget {
  const SafeAreaExample({super.key});

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      left: false,
      right: false,
      bottom: false,
      child: // Adding your widget here
    );
  }
}

huangapple
  • 本文由 发表于 2023年7月10日 21:16:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76654136.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定