【问题标题】:No MediaQuery widget ancestor found while using MediaQuery.of(context)使用 MediaQuery.of(context) 时未找到 MediaQuery 小部件祖先
【发布时间】:2021-05-26 05:05:50
【问题描述】:

我收到一条错误消息,提示 使用 MediaQuery.of(context) 时未找到 MediaQuery 小部件祖先。这是我的代码,我在 MaterialApp 中使用 MediaQuery.of(context) 但它仍然给我错误。有人可以帮忙吗?

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Responsive'),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                color: Colors.red,
                height: mediaQuery.size.height,
              ),
              Container(
                color: Colors.amber,
                height: 200,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

错误

【问题讨论】:

  • 您只能为context 调用MediaQuery.of,它是MaterialApp 的子(直接或间接) - 例如:runApp(MaterialApp(body: MyApp(), ...))
  • 不明白。您能否提供一个工作代码 sn-p 以便我理解?
  • 我已经给了你:而不是void main() => runApp(MyApp());void main() => runApp(MaterialApp(body: MyApp())); (当然从MyApp 中删除MaterialApp
  • 哎呀,对不起,应该是home:,当然不是body:
  • 是的!我试过这个void main() => runApp(MaterialApp(home: Scaffold(body: MyApp()))); 并且成功了,但是在主函数中包含这么多东西是一个好习惯吗?

标签: flutter dart


【解决方案1】:

您收到此错误是因为您的MediaQuery 超出了MaterialApp。将 material home 用作 Statefull 小部件的独立 Stateless。

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);

    return MaterialApp(
      home: Home();
  }
}

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('Responsive'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              color: Colors.red,
              height: mediaQuery.size.height,
            ),
            Container(
              color: Colors.amber,
              height: 200,
            ),
          ],
        ),
      ),
    );
  }
}

【讨论】:

    【解决方案2】:

    你需要像这样使用媒体查询

    Size size = MediaQuery.of(context).size;
    

    以及你想在哪里使用这样的宽度或高度

    height: size.height*0.1,
    

    【讨论】:

    • 没用!它给出了同样的错误。
    • 兄弟删除材料应用程序,您需要仅使用材料应用程序用户脚手架,然后它将为您工作
    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 2021-03-31
    • 2021-12-30
    • 2021-12-22
    • 2022-01-12
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    相关资源
    最近更新 更多