skip to Main Content

I am trying to add multiple data to Sqflite in flutter but it’s not working.

For example I want to add a list of a Todo class.

Pls if there’s any help I’ll appreciate.

I tried writing a raw SQL to add the list of data but it didn’t work. All I was getting was bunch of errors.

2

Answers


  1. actually there is no way you could insert all data by one function but you could do it with help of loops.
    you could tiger loop while the length of the list and do the insert while its true! its too simple

    List<Todo>todos=[Todo('example'),Todo('example'),Todo('example'),Todo('example')];
    //here should be the db provide class
    for(Todo iteam in todos){
       // do the insert functionality
       // here try the way you insert single todo in db
       db.insert(iteam.toJson())
    }
    
    
    
    Login or Signup to reply.
  2. To add a list of Todo class objects to Sqflite in Flutter, you can follow these steps:

    1. Create a database helper class that extends the DatabaseProvider class from the sqflite package. You can use this class to define methods for creating, opening, and updating the database.
    import 'package:sqflite/sqflite.dart';
    import 'package:path/path.dart';
    
    class DatabaseHelper {
      static final DatabaseHelper instance = DatabaseHelper._instance();
      static Database? _db;
    
      DatabaseHelper._instance();
    
      Future<Database> get db async {
        if (_db == null) {
          _db = await _initDb();
        }
        return _db!;
      }
    
      Future<Database> _initDb() async {
        final String dbPath = await getDatabasesPath();
        final String path = join(dbPath, 'todo_db.db');
    
        final todoDb = await openDatabase(path, version: 1, onCreate: _createDb);
    
        return todoDb;
      }
    
      void _createDb(Database db, int version) async {
        await db.execute(
            'CREATE TABLE todos(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, description TEXT, isDone INTEGER)');
      }
    
      Future<List<Map<String, dynamic>>> getTodosMapList() async {
        final Database db = await instance.db;
        final List<Map<String, dynamic>> result = await db.query('todos');
        return result;
      }
    
      Future<int> insertTodoList(List<Todo> todoList) async {
        final Database db = await instance.db;
        final Batch batch = db.batch();
    
        for (Todo todo in todoList) {
          batch.insert('todos', todo.toMap());
        }
    
        final List<dynamic> result = await batch.commit();
        final int affectedRows = result.reduce((sum, element) => sum + element);
        return affectedRows;
      }
    }
    
    1. Define a Todo class that contains the data you want to store in the database. In this example, the Todo class has four properties: id, title, description, and isDone.
    class Todo {
      int? id;
      String? title;
      String? description;
      bool? isDone;
    
      Todo({
        this.id,
        this.title,
        this.description,
        this.isDone = false,
      });
    
      Map<String, dynamic> toMap() {
        return {
          'id': id,
          'title': title,
          'description': description,
          'isDone': isDone ? 1 : 0,
        };
      }
    
      static Todo fromMap(Map<String, dynamic> map) {
        return Todo(
          id: map['id'],
          title: map['title'],
          description: map['description'],
          isDone: map['isDone'] == 1,
        );
      }
    }
    
    1. In the insertTodoList method of the DatabaseHelper class, create a batch object and use the insert method to insert each Todo object into the database. Finally, use the commit method to execute the batch.
    Future<int> insertTodoList(List<Todo> todoList) async {
      final Database db = await instance.db;
      final Batch batch = db.batch();
    
      for (Todo todo in todoList) {
        batch.insert('todos', todo.toMap());
      }
    
      final List<dynamic> result = await batch.commit();
      final int affectedRows = result.reduce((sum, element) => sum + element);
      return affectedRows;
    }
    
    1. To use the insertTodoList method to insert a list of `Todo
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search