Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Return Statements and Early Exits | Flow Control Techniques
Dart Control Flow

bookReturn Statements and Early Exits

メニューを表示するにはスワイプしてください

Return statements are a fundamental part of controlling the flow of your Dart functions. Whenever you use a return statement, you tell the function to stop executing and immediately send a value (or nothing, in the case of void functions) back to the caller. This is especially useful for exiting functions early, which can help you handle errors, invalid inputs, or special cases without running the rest of the code unnecessarily.

main.dart

main.dart

copy
123456789101112131415161718192021
String processUsername(String username) { // Check if the username is empty. if (username.isEmpty) { return 'Error: Username cannot be empty.'; } // Check if the username is too short. if (username.length < 4) { return 'Error: Username must be at least 4 characters long.'; } // If the username passes all checks, continue processing. // (Imagine more logic here, such as saving to a database.) return 'Username "$username" is valid and processed.'; } void main() { print(processUsername('')); // Error: Username cannot be empty. print(processUsername('abc')); // Error: Username must be at least 4 characters long. print(processUsername('dartdev')); // Username "dartdev" is valid and processed. }

Using early return statements, as shown in the username validation example, helps you write clearer and more maintainable code. Instead of nesting all your logic inside else blocks to handle errors or special cases, you can return immediately when a condition is met. This approach reduces indentation, makes each decision point obvious, and prevents the rest of the function from running when it should not. By returning early, you avoid unnecessary complexity and make the flow of your functions easier to follow, especially when dealing with multiple checks or validations.

question mark

Which of the following best describes the benefit of using return statements for early exits in Dart functions, as shown in the username validation example?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  1
some-alt