Flutter How can i save my date in Share preferences

1,366

Solution 1

convert it to a string & save it

prefs.setString('dateTimeString', _dateTime.toIso8601String());

then use DateTime.parse() to retrieve it:

DateTime _dateTime = DateTime.parse(prefs.getString('dateTimeString'));

Solution 2

Also you could take a look at the Flutter Secure Storage package. Here: https://pub.dev/packages/flutter_secure_storage I have used it in my projects and it works like a charm. Its as simple as importing the package and doing this:

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);
Share:
1,366
Teepause
Author by

Teepause

Updated on December 14, 2022

Comments

  • Teepause
    Teepause over 1 year

    I want to save my date thats picked from a DateTime-picker in a shared preferences so it will also be showen after restart the app

    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],
                            ),
                          ),
                        ),