欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

flutter 报错之 No MediaQuery widget found.

程序员文章站 2022-05-25 19:06:26
...

这里通过一个HelloWorld app来展示如何创建一个Widget并展示出来,并区分Material和非Material环境。
hello_word.dart里的代码如下:  MaterialApp

class HelloWorld {
  static Widget helloWorld() {
    return new MaterialApp(
      title: 'Hello World',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Scaffold(
        appBar: new AppBar(title: new Text('Hello World')),
        body: new Center(
            child: new Text(
          "Hello World",
          style: new TextStyle(fontSize: 32.0),
        )),
      ),
    );
  }

  static Widget hellWorldWithoutMaterial() {
    return new Container(
      decoration: new BoxDecoration(color: Colors.white),
      child: new Center(
        child: new Text(
          'Hello World',
          textDirection: TextDirection.ltr, // 这一句必须有
          style: new TextStyle(color: Colors.black, fontSize: 40.0),
        ),
      ),
    );
  }
}

而在展示上,主要的区别在于非Material下,没有Appbar、背景色和标题等,所有的内容都需要自定义。

注意⚠️:

1、Scaffold必须放在MaterialApp里面,否则会报错,大致如下:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building Scaffold(dirty, state: ScaffoldState#6f74d):
No MediaQuery widget found.
Scaffold widgets require a MediaQuery widget ancestor.
The specific widget that could not find a MediaQuery ancestor was:
Scaffold
The ownership chain for the affected widget is:
Scaffold ← MyApp ← [root]
Typically, the MediaQuery widget is introduced by the MaterialApp or WidgetsApp widget at the top of
your application widget tree.


 

相关标签: flutter