Flutter _ No MediaQuery widget ancestor found

769 阅读1分钟

错误源代码如下:

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

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


  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: Size(360,690),
        builder: () => MaterialApp(
          title: 'NFTicket',
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          // home: const MyHomePage(title: 'NFTicket'),
          home: const SelectAccount(),
          builder: (BuildContext context,Widget? child){
            return FlutterSmartDialog(child: child);
          },
        )
    );
  }
}

查找了一下说是在界面的根组件 , 没有使用 MaterialApp 组件 最后代码修改如下:

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

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


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'NFTicket',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      // home: const MyHomePage(title: 'NFTicket'),
      home: MainPage(),
      builder: (BuildContext context,Widget? child){
        return FlutterSmartDialog(child: child);
      },
    );
  }
}

class MainPage extends StatefulWidget{
  const MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();

}

class _MainPageState extends State<MainPage>{
  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
        BoxConstraints(
      maxWidth: MediaQuery.of(context).size.width,
      maxHeight: MediaQuery.of(context).size.height),
      designSize: const Size(360, 690),
      orientation: Orientation.portrait
    );
    return const Scaffold(
      body: SelectAccount(),
    );
  }
}

只是在以前的基础上添加了一层。感觉flutter这个层级真是有点。。。。