飞镖 - tolist()导致铸造例外

发布于 2025-02-13 10:12:14 字数 740 浏览 0 评论 0 原文

我正在尝试使用 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>'的值,但在 on Type'list< dynamic>' > .tolist()。

所有参数都是字符串类型,但是为什么会发生?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

叫思念不要吵 2025-02-20 10:12:14

请注意,我不是DART类型推理的专家,但这可能是正在发生的事情:

host mongodb 构造函数省略了特定类型信息,不给分析器足够的信息来推断您始终想要 list&lt; string&gt; 。因此,它假定它为 dynamic

有多种方法可以解决此问题:

  1. 在构造函数的参数中指定类型: mongodb({list&lt; strip&gt; strips&gt; strips = const ['myServer1',, 'myServer2','myServer3'],...})
  2. 指定您的 MAP 将始终返回字符串,因此 tolist()将产生 list&lt; string&gt; hosts.map&lt; string&gt;((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 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 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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文