Flutter : Facing an error like - The argument type 'Map<String, dynamic>?' can't be assigned to the parameter type 'Map<String, Object?>'

5,038

Solution 1

You are getting this error because in insert function the Map type is <String, Object?> and you are passing a map that's type is <dynamic, dynamic>. try changing

Map<dynamic, dynamic>? toMap() => {
        "id": colId,
        "name": colName.toString(),
        "mobile": colMobile.toString(),
      };

  factory Contact.fromMap(Map<dynamic, dynamic> json) =>
      Contact(name: json[colName], mobile: json[colMobile]); 

to

//You don't need to pass id because it's auto incremented

[ for null safety Use Map<String, Object?> not Map<String, Object>?]

Map<String, Object?> toMap() => {
        "name": colName.toString(),
        "mobile": colMobile.toString(),
      };

  factory Contact.fromMap(Map<String, Object?> json) =>
      Contact(name: json[colName], mobile: json[colMobile]);

Solution 2

Your DB says that he wants a map like

Map<String, Object>

here the map's key must be a String

And you are passing a map with dynamic type of key

so change the key of your map from dynamic to String

Change this map type

 Map<dynamic, dynamic>? toMap() => {
        "id": colId,
        "name": colName.toString(),
        "mobile": colMobile.toString(),
 };

to


 Map<String, dynamic>? toMap() => {
        "id": colId,
        "name": colName.toString(),
        "mobile": colMobile.toString(),
 };

After that you will get another error like

The argument type 'Map<String, dynamic>?' can't be assigned to the parameter type 'Map<String, Object?>'.

Now at first we have to undertand what that Map<String, Object?> mean?

The type Object is your maps value must me a specific type of Data like int double String or any Custom Object because SQL Database store data in column and each column must mantain a specific data type so try like this


 Map<String, Object>? toMap() => {
        "id": colId,
        "name": colName.toString(),
        "mobile": colMobile.toString(),
 };

Share:
5,038
Abir Ahsan
Author by

Abir Ahsan

Updated on December 30, 2022

Comments

  • Abir Ahsan
    Abir Ahsan over 1 year

    I am practicing with flutter SQFLite. That's why I create a model for user info. Here is my model code-

        class Contact {
          static const tblContact = "contacts";
          static const colId = "id";
          static const colName = "name";
          static const colMobile = "mobile";
        
          Contact({
            this.id,
            this.name = '',
            this.mobile = '',
          });
        
          int? id;
          String name;
          String mobile;
        
            Map<String, dynamic>? toMap() => {
            "id": colId,
            "name": colName.toString(),
            "mobile": colMobile.toString(),
          };
    
      factory Contact.fromMap(Map<String, dynamic> json) =>
          Contact(name: json[colName], mobile: json[colMobile]);
        }
    

    and then I create a database helper for insert and fetch data from database. But I faced a problem to insert value ( The argument type 'Map<dynamic, dynamic>?' can't be assigned to the parameter type 'Map<String, Object?>' ). Here is my database helper code -

    import 'dart:io';
    ......
    .......
    
    class DatabaseHelper {
      static const _databaseName = "ContactData.db";
      static const _databaseVersion = 1;
    
    //<====== Singleton Class
      DatabaseHelper._();
      static final DatabaseHelper instance = DatabaseHelper._();
    
      Database? _database;
      Future<Database?> get database async {
        if (_database != null) {
          return _database;
        } else {
          _database = await _initDatabase();
          return _database;
        }
      }
    
    //CREATE DATABASE
      _initDatabase() async {
        Directory dataDirectory = await getApplicationDocumentsDirectory();
        String dbPath = join(dataDirectory.path, _databaseName);
        print(dbPath);
        return await openDatabase(dbPath,
            version: _databaseVersion, onCreate: _onCreate);
      }
    
      //CREATE TABLE
      _onCreate(Database db, int version) async {
        db.execute(''' 
    CREATE TABLE ${Contact.tblContact}(
      ${Contact.colId} INTEGER PRIMARY KEY AUTOINCREMENT,
      ${Contact.colName} STRING NOT NULL,
      ${Contact.colMobile} STRING NOT NULL
    );
    ''');
        print("Done on Create");
      }
    
      //<===================  ADD DATA
    
      Future<int> insertContact(Contact contact) async {
        Database? db = await database;
    
        return await db!.insert(Contact.tblContact, contact.toMap());
      }
    
      //<==================== Read Data
      Future<List<Contact>> fetchContacts() async {
        Database? db = await database;
        List<Map<String, dynamic>> contacts = await db!.query(Contact.tblContact);
        print("Done Fetch");
        return contacts.length == 0
            ? []
            : contacts.map((x) => Contact.fromMap(x)).toList();
      }
    }
    

    Error :

    enter image description here

    Where is my problem and what I missed ? Please someone help me to solve this.

    Update: I change argument type "Map<dynamic, dynamic>?" to "Map<String, dynamic>?" but now I found another error .

    The argument type 'Map<String, dynamic>?' can't be assigned to the parameter type 'Map<String, Object?>'.
    

    Recent Error: enter image description here

  • Abir Ahsan
    Abir Ahsan almost 3 years
    I update my question. Please take a look. I found another error.
  • Abir Ahsan
    Abir Ahsan almost 3 years
    I update my question. Please take a look. I found another error.
  • Abir Ahsan
    Abir Ahsan almost 3 years
    I update my question. Please take a look. I found another error.
  • Hemal Moradiya
    Hemal Moradiya almost 3 years
    Can you please show me your insert function?
  • Abir Ahsan
    Abir Ahsan almost 3 years
    I already write in question [ Future<int> insertContact(Contact contact) async { Database? db = await database; return await db!.insert(Contact.tblContact, contact.toMap()); } ]
  • Saiful Islam
    Saiful Islam almost 3 years
    Yes, I got your problem. I predicted that already. I will update my answer soon.
  • Abir Ahsan
    Abir Ahsan almost 3 years
    I something change for null checker . Now everything fine, but I faced error for entry data to database ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: DatabaseException(datatype mismatch (code 20 SQLITE_MISMATCH[20])) sql 'INSERT INTO contacts (id, name, mobile) VALUES (?, ?, ?)' args [id, name, mobile]}. Can I create another question ? will you help me ?