-
Notifications
You must be signed in to change notification settings - Fork 506
Closed
Description
I want to be able to use ScreenUtil().Sp(20), for example, directly from my theme definition.
This is my actual code:
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _appTitle,
theme: _getAppTheme(), //HERE
home: HomePage(key, _appTitle),
builder: (BuildContext context, Widget widget) {
ScreenUtil.init(context,
width: 1080, height: 1920, allowFontScaling: true);
return Padding(
child: widget,
);
},
);
}
ThemeData _getAppTheme() {
return ThemeData(
primaryColorLight: Colors.blue,
primaryColorDark: Colors.deepPurple,
//...
primaryTextTheme: TextTheme(
bodyText1: TextStyle(
fontSize: ScreenUtil().setSp(16), //HERE: this is what I want to do
color: Colors.black87,
fontWeight: FontWeight.w400,
letterSpacing: 0.5),
),
);
}
But I got the Exception:
I/flutter ( 9488): The method 'setSp' was called on null.
Which make senses, because I'm calling _getAppTheme() before I init the ScreenUtil.
If I try to put the ScreenUtil.init(...) inside my _getAppTheme(), and modify it to receive the BuildContext parameter, as follows:
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _appTitle,
home: HomePage(key, _appTitle),
theme: _getAppTheme(context),
builder: (BuildContext context, Widget widget) {
.....
ThemeData _getAppTheme(BuildContext context) {
ScreenUtil.init(context, width: 1080, height: 1920, allowFontScaling: true);
return ThemeData(
primaryColorLight: Colors.blue,
....
It doesn't works, and throws this exception then:
I/flutter ( 9488): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 9488): The following assertion was thrown building Rpg3dit(dirty, state: _Rpg3ditState#e515c):
I/flutter ( 9488): MediaQuery.of() called with a context that does not contain a MediaQuery.
I/flutter ( 9488): No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
I/flutter ( 9488): This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce
I/flutter ( 9488): a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.
I/flutter ( 9488): The context used was:
I/flutter ( 9488): Rpg3dit
I/flutter ( 9488):
I/flutter ( 9488): The relevant error-causing widget was:
I/flutter ( 9488): Rpg3dit
package:rpg3dit/main.dart:12
I/flutter ( 9488):
I/flutter ( 9488): When the exception was thrown, this was the stack:
There's a way to workaround this? Is possible to use ScreenUtil inside the ThemeData definition?
Metadata
Metadata
Assignees
Labels
No labels