使用不包含MediaQuery的上下文调用MediaQuery.of()

时间:2019-06-04 14:52:04

标签: flutter

为什么会出现此错误?

不是MaterialApp提供的Mediaquery吗?我不太明白。

class Test extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: themeBuilder(context),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Title'),
        ),
        body: Container(
          alignment: Alignment.center,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'All their equipment and instruments are alive.',
              ),
              Text(
                'All their equipment and instruments are alive.',
                style: TextStyle(
                  fontSize: 34,
                  fontWeight: FontWeight.w700,
                ),
              ),
              GradientButton(
                child: Text('click me!'),
                onPressed: () {},
                width: MediaQuery.of(context).size.width,
              ),
              TextField()
            ],
          ),
        ),
      ),
    );
  }
}

我不知道我在做什么错。以前效果很好。

1 个答案:

答案 0 :(得分:0)

class Test extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
  return MaterialApp(
   title: Text('Title'),
   theme: themeBuilder(context),
   home: HomePage(),
  );
 }
}

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

   return Container(
     child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[

         ...

         GradientButton(
            child: Text('click me!'),
            onPressed: () {},
            width: MediaQuery.of(context).size.width,
          ),
         ]
     ),
   );
 }
}

尝试一下,让我知道进展如何