Kagimura
Kagimura

Reputation: 417

Saving DateTime type in Local File in Flutter

I have a form with a TextField and a submit button that is able to save and read the data.

class Storage {
  Future<String> get localPath async {
    final dir = await getApplicationDocumentsDirectory();
    return dir.path;
  }

  Future<File> get localFile async {
    final path = await localPath;
    return File('$path/db.txt');
  }

  Future<String> readData() async {
    try {
      final file = await localFile;
      String body = await file.readAsString();

      return body;
    } catch (e) {
      return e.toString();
    }
  }

  Future<File> writeData(String data) async {
    final file = await localFile;
    return file.writeAsString('$data');
  }
}

  @override
  void initState() {
    super.initState();
    widget.storage.readData().then((String value) {
      setState(() {
        name = value;
      });
    });
  }
  Future<File> writeData() async {
    setState(() {
      name = oneController.text;
      oneController.text = '';
    });
  }

With this I was able to save data with String values. I tried doing the same thing for DateTime and I get this error:
"The argument type 'Null Function(DateTime)' can't be assigned to the parameter type 'FutureOr Function(String)'"

Does saving to local file only work for String Data?

Upvotes: 0

Views: 2671

Answers (2)

Pablo Barrera
Pablo Barrera

Reputation: 10983

The error you are getting seems to be because you are trying to do this:

widget.storage.readData().then((DateTime value) {
  setState(() {
    name = value;
  });
});

Using DateTime as an argument, but it seems you forgot to change the return type of readData() to Future<DateTime>. Anyway, that's seems to be the error.

But as @Adrian mentioned, you could store the int property millisecondsSinceEpoch instead of DateTime, and then you could do this:

DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestampSaved);

Upvotes: 1

Adrian Murray
Adrian Murray

Reputation: 2314

To answer the other issue, you have to save strings to files. An object must be converted to a string. A typical way to save DateTime is to do something like millisecondsSinceEpoch and save that in your file.

Rather than reinvent what's been done before, I suggest looking into packages/plugins for persistent storage. One promising one is hive. You can search for more at pubdev. There you can find persistent storage options like shared_preferences, sqflite, and sembast. A couple of these (sembast and hive) are basically object stores within files. Kind of like what you're trying to do here.

Upvotes: 0

Related Questions