Please help, master. I've been a few days looking for the solution about my problem, but until now I have not found it.
I have a text widget, above the widget there is a dropdown to select the fontsize, 20, 30 and 40.
My question is:
- How do I set the default fontsize to 20?
- How do I save the selected fontsize into sharedpreferences?
This is my code
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MaterialApp(
home: MyTextApp(),
));
}
class MyTextApp extends StatefulWidget {
@override
_State createState() => _State();
}
class _State extends State<MyTextApp> {
SharedPreferences prefs;
List<double> _fontSizeList = [20, 30, 40];
double _changeFontSize;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Text Widget'),
),
body: SingleChildScrollView(
child: Column(
children: [
Card(
margin: EdgeInsets.only(bottom: 3),
child: ListTile(
title: Text("Font Size"),
trailing: DropdownButtonHideUnderline(
child: DropdownButton(
isExpanded: false,
value: _changeFontSize,
items: _fontSizeList.map((myFontSize) {
return DropdownMenuItem(
child: Text(myFontSize.toString()),
value: myFontSize,
);
}).toList(),
onChanged: (value) {
setState(() {
_changeFontSize = value;
});
},
hint: Text("Select FontSize"),
),
),
),
),
Center(
child: Padding(
padding: const EdgeInsets.all(20),
child: Text(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
style: TextStyle(fontSize: _changeFontSize),
),
),
),
],
),
),
);
}
}
I am very grateful for the help
This is quite a simple task.
Firstly, you should have a function which is only called once to add the default fontsize:
Secondly, you want to have another two functions which allow you to update and retrieve the fontsize:
Retrieving function:
Updating function:
Lastly, you want to update your UI like so:
I would just like to mention if you want to use the font size through out your app I would highly suggest using the Provider package to allow easy access to the font size around your app.
Hope that helps!