ошибка при использовании библиотеки ScreenUtil во флаттере - PullRequest
1 голос
/ 05 августа 2020

Я пытаюсь использовать 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),
    );
  }

Ответы [ 4 ]

1 голос
/ 05 августа 2020

Попробуйте это.

Widget build(BuildContext context) {
return Builder(builder:(ctx){
ScreenUtil.init(ctx);
 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),
    );});
  }

Это представит новый контекст с новым MediaQuerry

1 голос
/ 05 августа 2020

Вы можете скопировать и вставить полный код ниже
Вы можете использовать builder из MaterialApp
фрагмент кода

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(),
    );
  }
}

рабочая демонстрация

введите описание изображения здесь

полный код

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}');
  }
}
1 голос
/ 05 августа 2020

Вы не можете получить доступ к MediaQuery.of(), если он установлен внутри MaterialApp() -> Scaffold(). По сути, вы хотите разделить свой код на другой виджет, а затем получить к нему доступ.

0 голосов
/ 31 августа 2020

Вы можете использовать подключаемый модуль screenutil, убедитесь, что есть проблема с вашим использованием

ScreenUtil.init следует использовать в подкомпонентах MaterialApp。 следующим образом:

 @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Module',
        builder: FlutterBoost.init(postPush: _onRoutePushed),
        home: EmptyPage());
  }
·······
class EmptyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 320, height: 568, allowFontScaling: false);
    return Scaffold(
      body: Container(),
    );
  }
}

Если вы хотите использовать его снаружи, вы можете использовать v3. https://pub.dev/packages/flutter_screenutil/versions/3.0.0-beta.2 Внимательно прочтите документ

...