Home > Blockchain >  dart - toList() causes the casting exception
dart - toList() causes the casting exception

Time:07-06

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().

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

CodePudding user response:

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()
  • Related