-2

I'm trying to learn Flutter on my own and trying to build a chat app which is connected to the OpenAI api. It works fine, I can send messages and receive answers as well, but every time I close the app all of the messages are gone. I will add Firebase to the project later. Is there any solution to save the chat history to the device/app so I can have it locally and it will be there next time I open the app?

Ballazx
  • 431
  • 4
  • 12
  • 3
    There are many possible solutions. Check out this question https://stackoverflow.com/questions/75742236/flutter-local-database-storage/75742375#75742375 – Jozott Mar 25 '23 at 12:40
  • While not strictly related to your question, connecting to OpenAI APIs directly from a mobile app would expose your API key, which is not something you would want. – Riwen Jun 06 '23 at 16:58

1 Answers1

1

You can use the shared_preferences pub.dev package in order to achieve that. For exaple, if you wish to persist String data, you could do something similar to the below:

  /// Initializes the shared preferences object to be used in this class.
  Future<SharedPreferences?> initializePreferences() async {
    preferences = await SharedPreferences.getInstance();
    return preferences;
  }

  /// Used to persist String data.
  Future<void> persist(String key, String data) async {
    await preferences?.setString(key, data);
  }

  /// Retrieves persist data of type String.
  String? getString(String key) {
    String? data = preferences?.getString(key);
    return data;
  }

You can persist & retrieve various types of data (objects, lists, list of objects etc) by serializing / deserializing them as JSON objects. A full example of a sample data persist service can be found at black-out/data_persist_service/.

Hope it helps.
Cheers,