flutter - 在 flutter 中使用 ScreenUtil 库时出错

标签 flutter dart

我正在尝试使用 ScreenUtil() 使我的文本字体大小响应。 此行导致错误“ScreenUtil.init(context);”。 错误是“MediaQuery.of() 使用不包含 MediaQuery 的上下文调用。

Widget build(BuildContext context) {


ScreenUtil.init(context);

return MaterialApp(
    title: 'Meals App',
    theme: ThemeData(
      primarySwatch: Colors.pink,
      accentColor: Colors.amber,
      canvasColor: Color.fromRGBO(255, 254, 229, 1),
      fontFamily: 'Raleway',
      textTheme: TextTheme(
        headline6: TextStyle(
          fontSize: ScreenUtil().setSp(100),
          fontFamily: 'RobotoCondensed',
          fontWeight: FontWeight.bold,
        ),
        bodyText1: TextStyle(color: Color.fromRGBO(20, 51, 51, 1)),
        bodyText2: TextStyle(color: Color.fromRGBO(20, 51, 51, 1)),
      ),
    ),
    home: TabsScreen(favouriteMeals),
    );
  }

最佳答案

您可以在下面复制粘贴运行完整代码
您可以使用 MaterialAppbuilder
代码片段

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter_ScreenUtil',
      builder: (context, widget) {
        ScreenUtil.init(context,
            width: 750, height: 1334, allowFontScaling: false);
        return widget;
      },
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

工作演示

enter image description here

完整代码

import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

void main() => runApp(MyApp());

class TextStyles {
  TextStyle t1 = TextStyle(fontSize: 24.ssp, color: Colors.black);
  TextStyle t2 = TextStyle(fontSize: 24.sp, color: Colors.black);
}

var ts = TextStyles();

class TextStyle2 {
  static TextStyle2 ts2;

  factory TextStyle2() {
    if (ts2 == null) {
      ts2 = TextStyle2();
    }
    return ts2;
  }

  TextStyle t1 = TextStyle(fontSize: 24.ssp, color: Colors.black);
  TextStyle t2 = TextStyle(fontSize: 24.sp, color: Colors.black);
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter_ScreenUtil',
      builder: (context, widget) {
        ScreenUtil.init(context,
            width: 750, height: 1334, allowFontScaling: false);
        return widget;
      },
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //Set the fit size (fill in the screen size of the device in the design) If the design is based on the size of the iPhone6 ​​(iPhone6 ​​750*1334)
    //ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);
    return ExampleWidget(title: 'FlutterScreenUtil Demo');
  }
}

class ExampleWidget extends StatefulWidget {
  const ExampleWidget({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _ExampleWidgetState createState() => _ExampleWidgetState();
}

class _ExampleWidgetState extends State<ExampleWidget> {
  @override
  Widget build(BuildContext context) {
    printScreenInformation();
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
                  width: 375.w,
                  height: 200.h,
                  color: Colors.red,
                  child: Text(
                    'My width:${375.w}dp \n'
                    'My height:${200.h}dp',
                    style: TextStyle(
                        color: Colors.white, fontSize: ScreenUtil().setSp(24)),
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
                  width: ScreenUtil().setWidth(375),
                  height: ScreenUtil().setHeight(200),
                  color: Colors.blue,
                  child: Text(
                      'My width:${0.5.wp}dp \n'
                      'My height:${ScreenUtil().setHeight(200)}dp',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: ScreenUtil().setSp(24))),
                ),
              ],
            ),
            Text('Device width:${ScreenUtil.screenWidthPx}px'),
            Text('Device height:${ScreenUtil.screenHeightPx}px'),
            Text('Device width:${ScreenUtil.screenWidth}dp'),
            Text('Device height:${ScreenUtil.screenHeight}dp'),
            Text('Device pixel density:${ScreenUtil.pixelRatio}'),
            Text('Bottom safe zone distance:${ScreenUtil.bottomBarHeight}dp'),
            Text('Status bar height:${ScreenUtil.statusBarHeight}dp'),
            Text(
              'Ratio of actual width dp to design draft px:${ScreenUtil().scaleWidth}',
              textAlign: TextAlign.center,
            ),
            Text(
              'Ratio of actual height dp to design draft px:${ScreenUtil().scaleHeight}',
              textAlign: TextAlign.center,
            ),
            SizedBox(
              height: ScreenUtil().setHeight(100),
            ),
            Text('System font scaling factor:${ScreenUtil.textScaleFactor}'),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                    'My font size is 24px on the design draft and will not change with the system.',
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 24.sp,
                    )),
                Text(
                    'My font size is 24px on the design draft and will change with the system.',
                    style: ts.t1),
              ],
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.title),
        onPressed: () {
          ScreenUtil.init(context,
              width: 1500, height: 1334, allowFontScaling: false);
          setState(() {});
        },
      ),
    );
  }

  void printScreenInformation() {
    print('Device width dp:${ScreenUtil.screenWidth}'); //Device width
    print('Device height dp:${ScreenUtil.screenHeight}'); //Device height
    print(
        'Device pixel density:${ScreenUtil.pixelRatio}'); //Device pixel density
    print(
        'Bottom safe zone distance dp:${ScreenUtil.bottomBarHeight}'); //Bottom safe zone distance,suitable for buttons with full screen
    print(
        'Status bar height px:${ScreenUtil.statusBarHeight}dp'); //Status bar height , Notch will be higher Unit px
    print(
        'Ratio of actual width dp to design draft px:${ScreenUtil().scaleWidth}');
    print(
        'Ratio of actual height dp to design draft px:${ScreenUtil().scaleHeight}');
    print(
        'The ratio of font and width to the size of the design:${ScreenUtil().scaleWidth * ScreenUtil.pixelRatio}');
    print(
        'The ratio of  height width to the size of the design:${ScreenUtil().scaleHeight * ScreenUtil.pixelRatio}');
    print('System font scaling:${ScreenUtil.textScaleFactor}');
    print('0.5 times the screen width:${0.5.wp}');
    print('0.5 times the screen height:${0.5.hp}');
  }
}

关于flutter - 在 flutter 中使用 ScreenUtil 库时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63260709/

相关文章:

flutter - 在Flutter中,将整个应用程序包装在WillPopScope中时,不会调用onWillPop

reactjs - Flutter (Dart) 中的 RSA 加密

flutter - 抖动自动填充有助于建议不起作用

firebase - 如何在 Firestore 中加入内部连接

flutter - 在 Dart 的列表中使用 map 或 for 循环有什么不同吗?

flutter - 如何通过 flutter 中的导航栏为单页 Web 应用程序实现动态滚动?

flutter - 用 flutter 在黑暗模式下切换图像

dart - Flutter - 创建自己的 snackbar 设计

flutter - 如何创建在事件菜单项上带有顶行的 Flutter 底部导航?

dart - 动画 Controller vsync 无法将 'this' 识别为有效表达式