Dart中Future<void>.then()为何需带参数?Flutter Camera场景疑问
Future<void> requires a callback with parameter in .then()? Great question, this is a common point of confusion when working with Dart's Future API, especially with Future<void>! Let me break this down clearly:
The Root of the Issue
In Dart, the then method of a Future<T> expects a callback function that accepts a single parameter of type T. When your future is Future<void>, T is void—so the callback still needs to have a parameter slot to match this type, even though there's no actual value being passed.
If you try to use a callback with no parameters (like then(() {})), the compiler throws an error because it can't match the expected signature (Function(void) vs Function()).
How to Handle It
You have a few clean options to work around this:
Use an underscore to ignore the parameter (this is what you're already doing, and it's the standard approach):
controller.initialize().then((_) { // Initialization complete logic here });The underscore tells Dart "I know this parameter exists, but I don't need to use it."
Explicitly type the parameter as
voidfor extra clarity:controller.initialize().then((void _) { // Initialization complete logic here });Switch to
async/await(recommended)—this modern syntax avoids thethencallback entirely and makes your code more readable:try { await controller.initialize(); // Initialization complete logic here } catch (e) { // Handle initialization errors here }async/awaitis generally preferred in Dart for asynchronous code because it flattens the callback chain and makes error handling more straightforward withtry/catch.
Why This Design?
Dart's Future API uses a generic signature that's consistent across all future types. Whether you have a Future<String>, Future<int>, or Future<void>, the then method follows the same pattern: it passes the future's resolved value to the callback. For Future<void>, the "value" is just a placeholder of type void, so the callback still needs to accept it to adhere to the generic contract.
内容的提问来源于stack exchange,提问作者Bruce Brookshire

