使用bool尝试共享首选项
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用bool尝试共享首选项相关的知识,希望对你有一定的参考价值。
这是我第一次使用Shared-preferences,但是当我单击该图标时不能在true和false之间切换,而在退出程序时不能保存该值,有人知道这有什么问题吗?你可以帮助我。谢谢。
“ )import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Shared preferences demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Shared preferences demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool select = true;
@override
void initState() {
super.initState();
_loadCounter();
}
_loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('select', true);
}
_incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return bool
bool boolValue = prefs.getBool('select');
return boolValue;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title),),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$select',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
child: Icon(Icons.add),
),);}}
_incrementCounter
方法以获取bool值,该值是从共享首选项中获取的未来值class _MyHomePageState extends State<MyHomePage> {
bool select;
@override
void initState() {
super.initState();
setInitialValue();
}
setInitialValue() async {
final value = await _incrementCounter();
setState(() {
select = value?? true;
});
}
_loadCounter(bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('select', value);
}
Future<bool> _incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return bool
bool boolValue = prefs.getBool('select');
return boolValue;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$select',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
_loadCounter(!select);
final value = await _incrementCounter();
setState(() {
select = value;
});
},
child: Icon(Icons.add),
),
);
}
}
以上是关于使用bool尝试共享首选项的主要内容,如果未能解决你的问题,请参考以下文章
在 android 首选项片段中使用 startService()