flutter字体大小切换案例 小字体,标准字体,大字体,超大字体案例
Android iOS设备带有选择记录
我的flutter项目版本
environment:
sdk: ‘>=3.4.4 <4.0.0’
图片案例
pubspec.yaml 添加依赖
# 屏幕尺寸适配 https://github.com/OpenFlutter/flutter_screenutilflutter_screenutil: ^5.9.3# 状态管理 https://github.com/rrousselGit/providerprovider: ^6.1.2# 本地存储 官方插件 https://github.com/flutter/pluginsshared_preferences: ^2.2.3
代码案例
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:provider/provider.dart';void main() async {await ScreenUtil.ensureScreenSize(); // 确保屏幕大小被正确设置runApp(MyApp());
}class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return ScreenUtilInit(designSize: const Size(360, 690), // 设计稿尺寸builder: (_, child) => MaterialApp(home: ChangeNotifierProvider(create: (context) => FontSizeProvider(),child: HomeScreen(),),),);}
}class FontSizeProvider with ChangeNotifier {double _fontSize = 1.0; // 默认字体大小double get fontSize => _fontSize;Future<void> loadFontSize() async {final prefs = await SharedPreferences.getInstance();_fontSize = prefs.getDouble('fontSize') ?? 1.0;notifyListeners();}Future<void> saveFontSize(double size) async {final prefs = await SharedPreferences.getInstance();await prefs.setDouble('fontSize', size);_fontSize = size;notifyListeners();}
}class HomeScreen extends StatelessWidget {@overrideWidget build(BuildContext context) {//var fontSizeProvider = Provider.of<FontSizeProvider>(context, listen: false);var fontSizeProvider = Provider.of<FontSizeProvider>(context);fontSizeProvider.loadFontSize(); // 加载字体大小设置return Scaffold(appBar: AppBar(title: Text('字体大小切换',style: TextStyle(fontSize:15.sp * fontSizeProvider.fontSize, // 根据fontSizeProvider调整字体大小),),),body: Center(child: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[Text('这是一段示例文本',style: TextStyle(fontSize: 15.sp *fontSizeProvider.fontSize, // 根据fontSizeProvider调整字体大小),),ElevatedButton(onPressed: () => fontSizeProvider.saveFontSize(0.8), // 小字体child: Text('小字体'),),ElevatedButton(onPressed: () => fontSizeProvider.saveFontSize(1.0), // 标准字体child: Text('标准字体'),),ElevatedButton(onPressed: () => fontSizeProvider.saveFontSize(1.2), // 大字体child: Text('大字体'),),ElevatedButton(onPressed: () => fontSizeProvider.saveFontSize(1.5), // 超大字体child: Text('超大字体'),),],),),);}
}