首页 > 解决方案 > 使用 MediaQuery.of(context) 时未找到 MediaQuery 小部件祖先

问题描述

我收到一条错误消息,提示在使用 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,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

错误

错误图像

标签: flutterdart

解决方案


您收到此错误是因为您MediaQueryMaterialApp. 使用材料主页作为 Statefull 小部件的独立无状态。

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,
            ),
          ],
        ),
      ),
    );
  }
}

推荐阅读