The Ultimate Guide to App Development with Flutter : Learning Dart : Functions

18 أغسطس، 2024

Functions

 

Functions are declared by specifying the return type, the name of the function, and the parameters within paranetheses. Void is used to specify the return type if nothing is returned.

// doesn't return anything but still executes some code
void main() {
  print('hello world');
}

// prints 'hello' but also returns the string 'complete'
String hello(int reps) {
  for (int i = 0; i < reps; i++) {
    print('hello');
  }
  return 'complete';
}

// returns a list of strings (List<String>)
List<String> people() {
  return ['John', 'Doe'];
}

Asynchronous functions are functions that can execute different commands at the same time – asynchronously.

An example of how this would be useful is in calling APIs (basically, trying to retrieve some sort of useful information or data that was programmed by someone else, from the web). If our function calls an API and assigns a variable to the API’s response, but our entire App is waiting for that function to finish executing in order to do something, then it isn’t very efficient. If we make this function asynchronous, the function calling the API can then execute at the same time that the App allows other functions to execute, or while the App does something else.

Within an asynchronous function, if we ever need our function to wait for some line of code to finish before we continue, we simply precede the code with the keyword, ‘await’.

For asynchronous functions in dart, add the ‘async’ keyword between the parentheses and the curly braces, and enclose the return type in ‘Future<[return type]>’.

Future<String> retrieveData() async {
  String response = await someAPICall(); // assuming the api call returns a string
  return response;
}

 

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *