我正在尝试使用 aGestureDetector
来允许用户通过捏合来更改字体大小:
class _PinchToScaleFontState extends State<PinchToScaleFont> {
double _baseFontScale = 1;
double _fontScale = 1;
ThemeData _themeData;
@override
Widget build(BuildContext context) {
return GestureDetector(
child: Theme(
data: _themeData,
child: widget.child // The desired outcome is that all Text is resized
),
onScaleStart: (ScaleStartDetails scaleStartDetails) {
_baseFontScale = _fontScale;
},
onScaleUpdate: (ScaleUpdateDetails scaleUpdateDetails) {
// don't update the UI if the scale didn't change
if (scaleUpdateDetails.scale == 1.0) {
return;
}
setState(() {
double fontScale = (_baseFontScale * scaleUpdateDetails.scale).clamp(0.5, 5.0);
_updateFontScale(fontScale);
SharedPreferences.getInstance().then((prefs) => prefs.setDouble('fontScale', fontScale));
});
},
);
}
我可以获得以下代码来调整 a 的比例TextField
,但它不会调整任何Text
小部件的大小。
_updateFontScale(double fontScale) {
setState(() {
_fontScale = fontScale;
ThemeData theme = Theme.of(context);
/// This doesn't seem to work at all
// _themeData = theme.copyWith(textTheme: theme.textTheme.merge(TextTheme(bodyText2: TextStyle(fontSize: 14 * fontScale))));
/// This works for `TextField` but not `Text`
_themeData = theme.copyWith(textTheme: theme.textTheme.apply(fontSizeFactor: fontScale)); // merge(TextTheme()));
});
// }
}
真奇怪。在下面的代码中,我可以在下次加载整个应用程序时使用保存的 fontScale 来初始化整个应用程序的字体大小,但是为什么上面的代码(似乎正在访问相同的主题属性)不会给出相同的结果?
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
double savedFontScale = (await SharedPreferences.getInstance()).getDouble('fontScale') ?? 1.0;
runApp(MyApp(savedFontScale));
}
class MyApp extends StatelessWidget {
final double fontScale;
MyApp(this.fontScale);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: APP_NAME,
theme: ThemeData(
textTheme: TextTheme(
/// This works for all `Text` widgets - but you've got to restart the app
bodyText2: TextStyle(fontSize: 14 * fontScale),
...
home:
...
PinchToScaleFont(
...
TextField('This _will_ resize '),
Text('This will not resize, but it should '),