Dart报错‘List类没有无参构造函数’,如何创建Server列表?
修复Dart中“List类没有无参构造函数”错误
在Dart 2.0及以后版本中,List的无参构造函数已被移除,因此使用new List<Server>()创建列表会触发该错误。以下是两种直接有效的修复方式:
方法一:使用列表字面量创建可增长列表
这是最简洁的写法,直接通过字面量声明空的可增长列表:
var myServers = <Server>[];
方法二:使用List.empty构造函数并启用可增长
如果需要更明确地声明列表属性,可以通过List.empty构造函数指定growable: true:
var myServers = List<Server>.empty(growable: true);
修改后的完整代码示例
class Server { final String country; final String ip; final String username; final String password; const Server( {required this.country, required this.ip, required this.username, required this.password}); static List<Server> allServers() { // 使用列表字面量创建空列表 var myServers = <Server>[]; myServers.add(const Server( country: "Italy", ip: "1.2.3.4.example.com", username: "user1", password: "password1" )); myServers.add(const Server( country: "United States", ip: "5.6.7.8.example.com", username: "user2", password: "password2" )); return myServers; } }
内容的提问来源于stack exchange,提问作者Sandman42
相关产品推荐
相关产品推荐

