如何以编程方式增加整个应用程序的字体大小?

Eri*_*nes 0 dart flutter

我在 Flutter 中有一个 MaterialApp,希望根据用户偏好在整个应用程序中放大文本。

根据答案,我能够创建一个通知程序,例如:

class PreferencesNotifier with ChangeNotifier {
  double textScaleFactor = 1.0;

  PreferencesNotifier();

  Future<void> initialize() async {
    var prefs = await SharedPreferences.getInstance();
    textScaleFactor = prefs.getDouble('textScaleFactor') ?? 1.0;
  }

  setTextScaleFactor(double x) {
    textScaleFactor = x;
    notifyListeners();

    SharedPreferences.getInstance().then(
      (prefs) {
        prefs.setDouble('textScaleFactor', textScaleFactor);
      },
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

...然后使用 MediaQuery,例如:

MediaQuery(
        data: MediaQuery.of(context).copyWith(
          textScaleFactor: preferencesNotifier.textScaleFactor,
        ),
        child: Widget()
      ),
Run Code Online (Sandbox Code Playgroud)

小智 5

要以编程方式增加 Flutter 中整个应用程序的字体大小,您可以在应用程序的根目录中使用 MediaQuery 小部件。该小部件允许您访问设备的媒体和显示信息,例如屏幕尺寸和当前文本比例因子。

MediaQuery(
  data: MediaQuery.of(context).copyWith(
    // Increase the text scale factor to 1.5
    textScaleFactor: 1.5,
  ),
  child: YourApp(),
),
Run Code Online (Sandbox Code Playgroud)