1.先看效果图
fontSize.gif
-
导入flutter_riverpod,main入口使用ProviderScope:
image.png
2.新建ChangeNotifier 文件,直接上代码:
class GlobalRespository extends ChangeNotifier {
static GlobalRespository? _instance;
factory GlobalRespository() {
_instance ??= GlobalRespository._privateConstructor();
return _instance!;
}
GlobalRespository._privateConstructor();
late double _fontSize = 16.0;
globalFontSize(double size) {
_fontSize = size;
notifyListeners();
}
double get fontSize => _fontSize;
}
final globalChangeProvider = ChangeNotifierProvider<GlobalRespository>((ref) {
return GlobalRespository();
});
- 把stateFullWidget 替换为ConsumerStatefulWidget 方便使用标签ref
class MyHomePage extends ConsumerStatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
ConsumerState<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends ConsumerState<MyHomePage> {
void _incrementCounter() {
Navigator.push(
context, MaterialPageRoute(builder: (context) => const Home()));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
style:
TextStyle(fontSize: ref.watch(globalChangeProvider).fontSize),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
4.第二页Slider控制字体大小
class Home extends ConsumerStatefulWidget {
const Home({super.key});
@override
ConsumerState createState() => _HomeState();
}
class _HomeState extends ConsumerState<Home> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
const SizedBox(height: 100,),
Slider(
value: ref.read(globalChangeProvider).fontSize,
min: 14.0,
max: 25.0,
activeColor:const Color(0xff78EDD0),
onChanged: (value) {
ref.read(globalChangeProvider.notifier).globalFontSize(value);
},
onChangeEnd: (value) {
ref
.read(globalChangeProvider.notifier)
.globalFontSize(double.parse(value.toStringAsFixed(2)));
},
),
Text('多少字号 -${ref.read(globalChangeProvider).fontSize}',style: TextStyle(fontSize: ref.watch(globalChangeProvider).fontSize),)
],
),
);
}
}
5.一个界面不可能只有一个字号大小Text,建议封装多个Text使用,然后以一个为标准大小设置
6.退出APP再进还是原选择字号,可以存本地,打开app时在取,
----------------还有说在用MaterialApp的ThemeData中使用textTheme设置统一字体,但我没搞懂多个不同字号字体设置, 后面需求变化没继续细究。