dart: function part

2. function

Function is the first citizen and an object in dart. In dart, everything is an object, so you can also pass the function as an argument to the function or object

1. Function definition method

There are three functions in Dart:

  • Position parameter function
  • named function
  • Anonymous function
Call method of location parameter function definition
  • Definition method of optional and required parameters
    • Optional parameters are wrapped in the form of [], which can be omitted and not added during the call
    • If package description is not in the form of [], this parameter is required
    • If you want to specify default values for optional parameters, you can directly add the default values of parameters by * * = + [default] *
var favoriateFruit = {"Apple", 'Banana', 'A mandarin orange'};
var fruitMap = {"Apple": 5.5, 'Banana': 3.99, 'A mandarin orange': 6.8};

// Functions without parameters
dynamic getFruitPrice() {
  print(favoriateFruit);
  print(fruitMap);
}

// Multiple logics need to be defined with function expressions
// Unnamed function definition method
// The function named by position parameter needs to wrap the corresponding function name through [] if it needs to add anonymous function
dynamic getPrice(String fruit, [String notes = 'default notes']) {
  if (notes != null) {
    print('notes = $notes');
  }

  if (favoriateFruit.contains(fruit)) {
    return fruitMap[fruit];
  }

  return null;
}

  • How to call position parameter function
void main(){
  var price = getPrice('Banana', 'Look at the price of bananas');
  // Optional parameters can not be assigned first, and default assignment can be enabled.
  var nullPrice = getPrice('Pitaya');
  print(price);
  print(nullPrice);
}
/*
notes = Look at the price of bananas
notes = Default notes
3.99
null
*/
How to call a named function

How to define optional and non optional functions

  • When defining a function, an object similar to set is passed in
  • If it is a required parameter, it needs to be declared with @ required
  • All parameters not declared through required are optional
  • @required is defined in meta.dart, so you need to add a meta package when using it, otherwise an error will be reported
  • The method of setting the default parameter is the same as that of the named function
import 'package:meta/meta.dart';

void addFruit(
    {String fruit = "", double price = 100.0, @required String notes}) {
  favoriateFruit.add(fruit);
  fruitMap[fruit] = price;
  print(notes);
}

The method of adding meta package can be solved by calling flitter package. Specific method

  1. Create a pubspec.yaml file

    1. Just fill in the following code
name: demo
description: A new Dart project.
#Mainly this dependence
dependencies:
  flutter:
    sdk: flutter

How to call a named function

addFruit(fruit: 'Strawberry', price: 23.5, notes: 'Increase strawberry');
// Use default when price is not passed in
addFruit(notes: 'Winter melon, price unknown', fruit: 'Wax gourd');
getFruitPrice();
/*
    Increase strawberry
    Winter melon, price unknown
    {Apple, banana, orange, strawberry, wax gourd}
    {Apple: 5.5, banana: 3.99, Orange: 6.8, strawberry: 23.5, winter melon: 100.0}
*/
Definition of anonymous function
    List<Map<String, String>> fruitList = [
        {"fruit": "Durian", "price": "32"},
        {"fruit": "pineapple", "price": "3.5"}
    ];
  	
	// The following two results are identical
	// How to use anonymous functions
    fruitList.forEach((elem) {
        String str = "${elem['fruit']}The price is ${elem['price']}";
        print(str);
    });

    // If the expression has only one sentence, you can use the arrow function
    fruitList.forEach((elem) => print("${elem['fruit']}The price is ${elem['price']}"));

	/*
        The price of durian is 32
        A catty of pineapple costs 3.5
        The price of durian is 32
        A catty of pineapple costs 3.5
	*/
2. Function passed in as parameter
  	// Function is the first citizen can pass function to function
    // Define a handler for each
    void addFruitByList(Map<String, String> elem) {
      addFruit(
          notes: 'Bulk fruit',
          fruit: elem['fruit'],
          price: double.parse(elem['price']));
    }

    void main() {
        fruitList.forEach(addFruitByList);
        getFruitPrice();    
    }
	/*
        Bulk fruit
        Bulk fruit
        {Apple, banana, orange, strawberry, wax gourd, durian, pineapple}
        {Apple: 5.5, banana: 3.99, Orange: 6.8, strawberry: 23.5, winter melon: 100.0, durian: 32.0, pineapple: 3.5}
	*/
3. scope of action

Function scope is different from JS. Variables defined by var or const are deadband from within function scope to before variables are defined

void forScope() {
  // After the variable is determined, there will be a dead zone between the var and the const in js. Therefore, the value of the external variable can no longer be obtained if the same variable is defined as the external variable
  // There will be a mistake here
  // print(fruitMap);

  var fruitMap = {'test'};
  print('I'm on the first floor=$fruitMap');

  void Second() {
    var fruitMap = {'The second floor'};
    print('I'm on the second floor=$fruitMap');
  }

  Second();
}

/*
    I'm the first layer = {test}
    I am the second layer = {the second layer}
*/
3. Use of closure syntax

Using closures can achieve corrilization, which is completely consistent with the method used in JS. No more details are required

// Use of closure syntax
dynamic definePriceChanger(String fruit) {
  if (fruitMap.keys.contains(fruit)) {
    print('$fruit Price can change');
    return (num price) {
      fruitMap[fruit] = price;
    };
  } else {
    return ([num _noParam]) {
      print('Fruit price cannot be modified');
    };
  }
}

void main() {
	var changeBanana = definePriceChanger('Banana');
    getFruitPrice();
    changeBanana(2.99);
    getFruitPrice();
}
/*
    {Apple, banana, orange, strawberry, wax gourd, durian, pineapple}
    {Apple: 5.5, banana: 3.99, Orange: 6.8, strawberry: 23.5, winter melon: 100.0, durian: 32.0, pineapple: 3.5}
    {Apple, banana, orange, strawberry, wax gourd, durian, pineapple}
    {Apple: 5.5, banana: 2.99, Orange: 6.8, strawberry: 23.5, winter melon: 100.0, durian: 32.0, pineapple: 3.5}
*/
77 original articles published, 6 praised, 20000 visitors+
Private letter follow

Tags: SDK

Posted on Tue, 04 Feb 2020 00:27:45 -0500 by StathisG