key
key

Reputation: 1404

getting error: The argument type 'Product' can't be assigned to the parameter type 'Map<String, dynamic>

I'm trying to add some new data but get the error:

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

Here is what I'm trying to do: I have a form with simply 2 TextFields I've declared a map with the data

final Map<String, dynamic> _formData = {
      'title': null,
      'content': null,
    };

and afterwards I'm using the bloc to pass the data with the model constructor Product

RaisedButton(
                child: Text('Add'),
                  onPressed: () {
                  bloc.createData(
                    Product(
                        title: _formData['title'],
                        content: _formData['description'],
                  )
                  );
                }
              ),

in the bloc I pass it to the provider like so:

  void createData(Product product) async {
    String id = await db.createData(product);
    _inId.add(id);
  }

And here it comes:

Future createData(Product product) async {
    DocumentReference ref = await db.collection("product").add(product); //error: The argument type 'Product' can't be assigned to the parameter type 'Map<String, dynamic>
    print(ref.documentID);
    return ref.documentID;
}

as I'm using the collection_reference and it takes a map I cannot use the argument model Products, which is constructed like so:

class Product {

  final String title, content;

  Product({this.title, this.content});

}

Upvotes: 1

Views: 12592

Answers (1)

Manish Dhruw
Manish Dhruw

Reputation: 803

You need to convert product to Map

Example:

Future createData(Product product) async 
{ 
    await db.collection("product").add( _convertProductToMap(product));
}

Map<String, dynamic> _convertProductToMap( Product product )
{
    Map<String, dynamic> map = {};
    map['title'] = product.title;
    map['content'] = product.content;

   return map;
}

you will also need to convert back map into Product object after retriving data from db

Upvotes: 2

Related Questions