Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

dart – toList() causes the casting exception

I’m trying to connect to MongoDB from my code using mongo_dart package.

So my approach is below,

import 'package:mongo_dart/mongo_dart.dart';

class MongoDB {
  late Db db;

  MongoDB(
      {hosts = const ['myserver1', 'myserver2', 'myserver3'],
      port = '27017',
      username = 'admin',
      password = 'mypassword',
      dbname = 'mydb',
      authSource = 'admin'}) {
    db = Db.pool(
        hosts.map((elem) => "mongodb://$username:$password@$elem:$port/$dbname?authSource=$authSource").toList());
  }

When executing this code an exception occurs which has the message Expected a value of type 'List<String>', but got one of type 'List<dynamic>' on .toList().

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

All the parameters are string types, but why does it happen?

>Solution :

Please be aware that i am not an expert on Dart’s type inference, but this is probably what is happening:

The host argument for your MongoDB constructor omits specific type information, which does not give the analyzer enough information to infer that you always want a List<String>. So it assumes it to be List<dynamic>

There are multiple way to fix this:

  1. Specify the type in the arguments of the constructor: MongoDB({List<String> hosts = const ['myserver1', 'myserver2', 'myserver3'], ...})
  2. Specify that your map will always return a String and thus toList() will produce a List<String>: hosts.map<String>((elem) => "mongodb://$username:$password@$elem:$port/$dbname?authSource=$authSource").toList()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading