我想将从DateTime选择器中选择的日期保存在共享首选项中,这样它也会在重新启动应用后显示
child: InkWell(
onTap: (){
DatePicker.showDateTimePicker(context,
showTitleActions: true,
minTime: DateTime.now().toLocal(),
onConfirm: (date){
setState(() {
_dateTime = date;
});
},
currentTime: DateTime.now().toLocal(),
locale: LocaleType.de
);
},
child: Text(
(_dateTime == null ? 'Wählen sie Ihren nächsten Termin' : DateFormat("dd-MM-yyyy hh:mm").format(_dateTime)),
style: TextStyle(
fontSize: data.size.height / 29,
color: Colors.grey[400],
),
),
),
将其转换为字符串&保存
prefs.setString('dateTimeString', _dateTime.toIso8601String());
然后使用DateTime.parse((检索它:
DateTime _dateTime = DateTime.parse(prefs.getString('dateTimeString'));
您还可以查看Flutter Secure Storage软件包。此处:https://pub.dev/packages/flutter_secure_storage我在我的项目中使用过它,它就像一种魅力。它就像导入包并这样做一样简单:
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
// Create storage
final storage = new FlutterSecureStorage();
// Read value
String value = await storage.read(key: key);
// Read all values
Map<String, String> allValues = await storage.readAll();
// Delete value
await storage.delete(key: key);
// Delete all
await storage.deleteAll();
// Write value
await storage.write(key: key, value: value);
现在我做了这个:
FlutterSecureStorage storage;
@override
void initState() {
super.initState();
storage = FlutterSecureStorage();
}
@override
void dispose() {
super.dispose();
storage = null;
}
String testa;
并像这样使用它:
child: InkWell(
onTap: (){
DatePicker.showDateTimePicker(context,
showTitleActions: true,
minTime: DateTime.now(),
onConfirm: (date){
setState(() {
//_dateTime = date;
storage.write(key: SECURE_NOTE_KEY, value: date.toIso8601String());
testa = storage.read(key: SECURE_NOTE_KEY).toString();
});
},
currentTime: DateTime.now(),
locale: LocaleType.de
);
},
child: Text(
(testa == null ? 'Wählen sie Ihren nächsten Termin' : testa),
style: TextStyle(
fontSize: data.size.height / 29,
color: Colors.grey[400],
),
),
),
但它不起作用。。。。