如何解决“使用不包含MediaQuery的上下文调用的MediaQuery.of()”的错误? [英] How can I fix the error of "MediaQuery.of() called with a context that does not contain a MediaQuery."?

查看:332
本文介绍了如何解决“使用不包含MediaQuery的上下文调用的MediaQuery.of()”的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么在使用 Tab标签时会出现此错误像下面一样。每当我尝试构建
应用程序时,都会出现错误屏幕。

I don't know why this error comes out when I use "Tab" like below. Whenever I tried to build the app the error screen comes out. Please let me know how to fix it.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: Text('Tab'),
          bottom: TabBar(
            tabs: <Widget>[
              Tab(icon: Icon(Icons.tag_faces),),
              Tab(text: 'menu',),
              Tab(icon: Icon(Icons.info),text: 'menu',),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            Container(color: Colors.purple,),
            Container(color: Colors.purple,),
            Container(color: Colors.purple,),
          ],
        ),
      ),
    );
  }
}


推荐答案

您需要在MaterialApp中包装DefaultTabController。如果您访问脚手架类,则可以看到它需要MediaQuery。 MediaQuery在 WidgetsApp 类中定义。由于MaterialApp继承自WidgetsApp,因此包装我们的窗口小部件树将使Scaffold可以访问MediaQuery类。

You need to wrap DefaultTabController in MaterialApp. If you visit the Scaffold class then you can see that it needs MediaQuery. MediaQuery is defined in WidgetsApp class. Since the MaterialApp inherits from WidgetsApp hence wrapping our widget tree will allow the Scaffold to access MediaQuery class.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            title: Text('Tab'),
            bottom: TabBar(
              tabs: <Widget>[
                Tab(icon: Icon(Icons.tag_faces),),
                Tab(text: 'menu',),
                Tab(icon: Icon(Icons.info),text: 'menu',),
              ],
            ),
          ),
          body: TabBarView(
            children: <Widget>[
              Container(color: Colors.purple,),
              Container(color: Colors.purple,),
              Container(color: Colors.purple,),
            ],
          ),
        ),
      ),
    );
  }
}

这篇关于如何解决“使用不包含MediaQuery的上下文调用的MediaQuery.of()”的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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