Search code examples
listdart

Dart List error The class 'List' doesn't have an unnamed constructor


I'm trying to create a List of servers in this way:

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 = new List<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;
  }
}

I get the error "The class 'List' doesn't have an unnamed constructor"

How can I fix it?

Thanks in advance


Solution

  • Your code is almost right but you have followed the wrong syntax.

    Please refer below example. I have just redraft your example

    
    void main() {
      final a = Server.allServers();
      print(a);
    }
    
    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() {
        /// Here is your mistake
        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;
      }
    }