Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

write code flutter save data without SharedPreferences

  1. User

    write code flutter save data without SharedPreferences

  2. Assistant

    To save data in Flutter without using SharedPreferences, you can use various other alternatives such as:

    1. Filesystem: Using Flutter's dart:io package, you can read and write data to files on the device's filesystem. Here's an example of how you can save a string value to a file:
    import 'dart:io';
    import 'dart:async';
    
    Future<File> _getFile() async {
      final directory = await getApplicationDocumentsDirectory();
      return File('${directory.path}/data.txt');
    }
    
    Future<void> saveData(String data) async {
      final file = await _getFile();
      await file.writeAsString(data);
    }
    
    1. SQLite Database: Using the sqflite package, you can save data in a SQLite database. Here's an example of how you can save a user object to a database:
    import 'package:sqflite/sqflite.dart';
    import 'package:path/path.dart';
    
    class User {
      final int id;
      final String name;
    
      User({this.id, this.name});
    }
    
    Future<Database> openDatabase() async {
      final String path = join(await getDatabasesPath(), 'users.db');
      return openDatabase(
        path,
        version: 1,
        onCreate: (Database db, int version) async {
          await db.execute(
            'CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT)',
          );
        },
      );
    }
    
    Future<int> saveUser(User user) async {
      final Database db = await openDatabase();
      return db.insert('users', user.toMap(),
          conflictAlgorithm: ConflictAlgorithm.replace);
    }
    

    These are just a few examples of how you can save data in Flutter without using SharedPreferences. Depending on your use case and requirements, you can choose the appropriate alternative.