Flutter共享的首选项在本地节省INT值
我正在构建一个页面,用户可以使用提供商
软件包选择一个喜欢的配置文件图片以显示应用程序。我使用 shared_preferences
将本地的配置文件图片首选项保存为 int
值。为此,我在资产文件夹中添加了15个SVG图像,用户只能为此目的选择其中一个。 SVG图像被更名为 1.SVG
, 2.SVG
... 15.svg
,因此我可以使用该<代码> int 值。
这是我创建的
class ProfilePicPref {
static const PRO_PIC_STS = 'PROFILESTATUS';
setProfilePic(int svgNo) async {
SharedPreferences profilePref = await SharedPreferences.getInstance();
profilePref.setInt(PRO_PIC_STS, svgNo);
}
Future<int> getProfilePicture() async {
SharedPreferences profilePref = await SharedPreferences.getInstance();
return profilePref.getInt(PRO_PIC_STS) ?? 1;
}
}
这是我创建的提供商类
class ProfilePicProvider with ChangeNotifier {
ProfilePicPref profilePicPreferences = ProfilePicPref();
int _svgNumber = 1;
int get svgNumber => _svgNumber;
set svgNumber(int value) {
_svgNumber = value;
profilePicPreferences.setProfilePic(value);
notifyListeners();
}
void changePic(int val) {
_svgNumber = val;
profilePicPreferences.setProfilePic(val);
notifyListeners();
}
}
or
这是小部件树。当用户点击配置文件映像时,它会更新当前。但不能保存该数据。 问题是,我必须手动保存代码,以查看先前选择的配置文件图像。有人请帮助我在本地保存经常帐户图片数据。
class SelectProfilePicture extends StatefulWidget {
const SelectProfilePicture({Key? key}) : super(key: key);
@override
State<SelectProfilePicture> createState() => _SelectProfilePictureState();
}
class _SelectProfilePictureState extends State<SelectProfilePicture> {
int svgNumber = 1;
ProfilePicProvider proProvider = ProfilePicProvider();
@override
void initState() {
getCurrentProfilePicture();
super.initState();
}
void getCurrentProfilePicture() async {
proProvider.svgNumber =
await proProvider.profilePicPreferences.getProfilePicture();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
CurrentAccountPicture(path: 'assets/svg/${proProvider.svgNumber}.svg'), // I want update this widget using users preferences. By default it is set to 1.svg
Center(
child: Text(
'Current Account Picture',
style: style(),
),
),
Expanded(
child: GridView.builder(
itemCount: 15,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
setState(() {
svgNumber = index + 1;
});
proProvider.changePic(index + 1);
},
child: SvgPicture.asset('assets/svg/${index + 1}.svg'),
);
},
),
),
],
),
);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您的svgnumber可以保存得很好。只是在从存储中读取它后,它不知道刷新页面。
由于您使用
changeNotifier
,因此可以编写代码来收听它。另外,我认为将读数放入
setstate
也应该解决它。所以喜欢:I think your svgNumber is saved just fine. It's just that after reading it from storage it doesn't know to refresh the page.
Since you use a
ChangeNotifier
you could write code to listen to it.Alternatively, I think that putting the reading in a
setState
should also solve it. So like: