Flutter Error: MediaQuery.of() called with a context that does not contain a MediaQuery

后端 未结 14 1115
借酒劲吻你
借酒劲吻你 2020-11-28 14:05

I have been trying to get the size of the whole context view in Flutter. But every time I try I\'m getting the above mentioned error. Here\'s my code:

impor         


        
14条回答
  •  隐瞒了意图╮
    2020-11-28 14:45

    There is better way. Above solutions would require you to have only one screen widget or inherit all screens from parent class. But there is solution, place the media query initialization into onGenerateRoute callback function

    main.dart

    import 'package:flutter/material.dart';
    
    class MyApp extends StatefulWidget {
        @override
        State createState() => new MyAppState();
    }
    
    class MyAppState extends State {
        @override
        Widget build(BuildContext context) {
          return MaterialApp(
            title: 'My Awesome App',
            routes: NavigationUtils.routeList(),
            onGenerateRoute: (routeSettings) =>
              NavigationUtils.onGenerateRoute(routeSettings),
          );
        }
    }
    

    NavigationUtils.dart

    import 'package:flutter/material.dart';
    
    class NavigationUtils {
        static onGenerateRoute(RouteSettings routeSettings) {   
          return new MaterialPageRoute(
            builder: (context) {
              WidgetUtils.me.init(context);
                return StorageUtils.me.isLogged() ? HomeScreen() : ForkScreen();
            },
            settings: routeSettings,
          );
        }
    }
    

    WidgetUtils.dart

    import 'package:flutter/material.dart';
    
    class WidgetUtils {
        MediaQueryData _mediaQueryData;
        double _screenWidth;
        double _screenHeight;
        double _blockSizeHorizontal;
        double _blockSizeVertical;
    
        init(BuildContext context) {
            _mediaQueryData = MediaQuery.of(context);
            screenWidth = _mediaQueryData.size.width;
            screenHeight = _mediaQueryData.size.height;
            blockSizeHorizontal = screenWidth / 100;
            blockSizeVertical = screenHeight / 100;
        }
    }
    

    Warning: It is not copy & paste code, there are some singletons etc. but you should get the point ;)

提交回复
热议问题