如何在Dart中一次性创建多个对象?
Hey there! I totally get where you're coming from—you want to initialize a collection of Player objects in Dart, similar to the array syntax you might use in Java (Player[] player = new Player[20];). Let me break down the proper ways to do this in Dart, since it handles collections a bit differently.
First, Define Your Player Class
First, let's make sure your Player class is set up properly (I'll add a constructor to make initialization easier):
class Player { var health; var level; // Optional constructor with default values for convenience Player({this.health = 100, this.level = 1}); }
Method 1: Use List.generate (Most Recommended)
Dart's equivalent of a Java array is a List, and the cleanest way to create multiple instances is using List.generate. This lets you create a list with a specified number of elements, and you can customize each instance as needed:
// Create 20 Player objects with default health/level values List<Player> players = List.generate(20, (index) => Player()); // Or customize each player (e.g., set level based on its position in the list) List<Player> players = List.generate(20, (index) => Player(level: index + 1));
The first parameter is the number of elements, and the second is a callback that creates each Player instance. This ensures every element is a separate, independent object—no shared references here!
Method 2: Fixed-Length List with Manual Initialization
If you prefer to create a fixed-length list first and then populate it manually, you can do this. Just be careful with the filled method (it has a gotcha!):
// ❌ Warning: This will make all elements reference the SAME Player object! // Don't use this if you need independent, mutable players List<Player> badPlayers = List<Player>.filled(20, Player(), growable: false); // ✅ Correct way to create a fixed-length list with independent players List<Player> players = List<Player>.empty(growable: false)..length = 20; for (int i = 0; i < 20; i++) { players[i] = Player(health: 80 + i*2, level: i + 1); }
The filled method reuses the same object for every position, which is almost never what you want for mutable classes like Player. The manual loop ensures each index gets its own new Player.
Method 3: List Literal (For Smaller Collections)
If you were creating just a few players, you could use a list literal, but this isn't practical for 20 instances:
List<Player> smallPlayerList = [ Player(), Player(level: 2), Player(health: 150), // ... repeat until you have 20 entries ];
Wrap-Up
For your use case (creating 20 Player objects), List.generate is the best choice—it's concise, flexible, and avoids common pitfalls.
内容的提问来源于stack exchange,提问作者Florent

