颤动-直接在材质应用中访问MediaQuery.ofcontext.size

问题描述

我想使我的应用程序具有响应能力,为此,我需要直接在材质应用程序中访问设备的宽度,以便主题可以调整其功能大小...当我尝试这样做时,这错误发生:MediaQuery.of() called with a context that does not contain a MediaQuery.

如何解决?

这是我主要班级的代码:


void main() {
  runApp(
      MultiProvider(
          providers: [
            ChangeNotifierProvider(create: (_) => PlayerProvider()),ChangeNotifierProvider(create: (_) => QuestionsProvider()),ChangeNotifierProvider(create: (_) => SettingsProvider()),ChangeNotifierProvider(create: (_) => CategoryProvider()),ChangeNotifierProvider(create: (_) => FirebaseMessagingProvider()),ChangeNotifierProvider(create: (_) => TeamQuestionsProvider()),ChangeNotifierProvider(create: (_) => AppLanguageProvider()),],child: BuvonsApp(),)
  );
}

// ignore: must_be_immutable
class BuvonsApp extends StatelessWidget {
  FirebaseAnalytics analytics = FirebaseAnalytics();
  BuildContext myContext;
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,]);
    Provider.of<FirebaseMessagingProvider>(context,listen: false).init();
    Provider.of<SettingsProvider>(context,listen: false).initSharedPreferences();
    Provider.of<AppLanguageProvider>(context,listen: false).fetchLocale();
    return Consumer<AppLanguageProvider>(builder: (context,model,child) {
      return MaterialApp(
        debugShowCheckedModeBanner: false,navigatorObservers: [
          FirebaseAnalyticsObserver(analytics: analytics),title: 'Buvons',theme: ThemeData(
          brightness: Brightness.light,sliderTheme: SliderThemeData(
              valueIndicatorColor: Colors.orange,valueIndicatorTextStyle: GoogleFonts.rubik(fontSize: ResponsiveSize().responsiveSize(17,context),fontWeight: FontWeight.bold,color: Colors.white)
          ),textTheme: GoogleFonts.rubikTextTheme()
              .copyWith(bodyText2: GoogleFonts.rubik(fontSize: ResponsiveSize().responsiveSize(17,color: Colors.white))
              .copyWith(subtitle1: GoogleFonts.rubik(fontSize: ResponsiveSize().responsiveSize(17,color: Colors.grey[700]))
              .copyWith(subtitle2: GoogleFonts.rubik(fontSize: ResponsiveSize().responsiveSize(17,color: Colors.grey[700]))
              .copyWith(headline5: GoogleFonts.rubik(fontSize: ResponsiveSize().responsiveSize(10,color: Colors.white)),appBarTheme: AppBarTheme(
            centerTitle: true,iconTheme: IconThemeData(color: Colors.white),textTheme: GoogleFonts.rubikTextTheme()

                .copyWith(headline6: GoogleFonts.rubik(fontSize: ResponsiveSize().responsiveSize(25,),tabBarTheme: TabBarTheme(
            labelColor: Colors.white,labelStyle: GoogleFonts.rubik(fontSize: ResponsiveSize().responsiveSize(15,fontWeight: FontWeight.bold),unselectedLabelColor: Colors.grey[100],unselectedLabelStyle: GoogleFonts.rubik(fontSize: ResponsiveSize().responsiveSize(13,primarySwatch: Colors.orange,splashColor: Colors.orangeAccent,secondaryHeaderColor: Colors.orangeAccent,dividerColor: Colors.orange,visualDensity: VisualDensity.adaptivePlatformDensity,home: SplashScreen(),navigatorKey: navigatorKey,locale: Provider.of<AppLanguageProvider>(context).appLocal,localizationsDelegates: [
          AppLocalizations.delegate,GlobalMaterialLocalizations.delegate,GlobalCupertinoLocalizations.delegate,GlobalWidgetsLocalizations.delegate,supportedLocales: [
          const Locale('en'),const Locale('fr'),const Locale('es'),// const Locale('de'),// const Locale('pl'),);
    },);
  }
}

根据设备的大小,这些ResponsiveSize().responsiveSize(15,context)将返回一个double值!

这是响应大小函数:

double responsiveSize(double size,BuildContext context) {
    double shortestSideSize = MediaQuery.of(context).size.shortestSide;
    if (shortestSideSize < 450) {
      return size;
    } else if (shortestSideSize >= 450 && shortestSideSize < 850) {
      return size*1.5;
    } else {
      return size*2;
    }
  }

解决方法

我通过@Bruno Hugentobler Lipper解决了问题

因此,我更改了功能,因此不必使用上下文并将其与主类放在同一文件中。

功能如下:

double _responsiveSize(double size) {
  double shortestSideSize = WidgetsBinding.instance.window.physicalSize.width/WidgetsBinding.instance.window.devicePixelRatio;
  if (shortestSideSize < 450) {
    return size;
  } else if (shortestSideSize >= 450 && shortestSideSize < 850) {
    return size*1.5;
  } else {
    return size*2;
  }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...