飞镖 - tolist()导致铸造例外
我正在尝试使用 mongo_dart
软件包从我的代码连接到MongoDB。
因此,我的方法在下面,
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());
}
当执行此代码时,会发生一个例外,该异常具有消息期望“列表”< string>'的值,但在
> .tolist()。 on Type'list< dynamic>'
所有参数都是字符串类型,但是为什么会发生?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,我不是DART类型推理的专家,但这可能是正在发生的事情:
host
mongodb
构造函数省略了特定类型信息,不给分析器足够的信息来推断您始终想要list< string>
。因此,它假定它为dynamic
有多种方法可以解决此问题:
mongodb({list< strip> strips> strips = const ['myServer1',, 'myServer2','myServer3'],...})
MAP
将始终返回字符串
,因此tolist()
将产生list< string>
:hosts.map< string>((ELEM)=&GT ; “ mongodb:// $ username:$ password@$ elem:$ port/$ dbname?authsource = $ authsource”).tolist()
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 yourMongoDB
constructor omits specific type information, which does not give the analyzer enough information to infer that you always want aList<String>
. So it assumes it to bedynamic
There are multiple way to fix this:
MongoDB({List<String> hosts = const ['myserver1', 'myserver2', 'myserver3'], ...})
map
will always return aString
and thustoList()
will produce aList<String>
:hosts.map<String>((elem) => "mongodb://$username:$password@$elem:$port/$dbname?authSource=$authSource").toList()