• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

1. List and map

List, the list in Dart:

  • Var list1 = [1, 2, 3];createvariableList.
  • Var list1 = const [1,2,3];createimmutableList.
  • You can store different types

Specifies the location to add elements.

list1.insert(0, "asd");
Copy the code

Deletes the specified element.

list1.remove("asd");
Copy the code

Clear all elements.

list1.clear();
Copy the code

Array sort.

list1.sort();
Copy the code

Take sublist(here the range is 1-2, that is, include the front but not the back).

List1. Sublist (1, 3);Copy the code

The list into the map

list1.asMap()
Copy the code

An error is reported if an immutable array operates on an array. map, key value pairs in DART.

  • var dic1 = {'one':'xiaolu','two':'xiaoshun'};createvariableList.
  • var dic1 = const {'one':'xiaolu','two':'xiaoshun'};createimmutableList.

A dictionary value

dic1["one"]
Copy the code

Get dictionary length

dic1.length;
Copy the code

Gets all the values of the dictionary

 dic1.values;
Copy the code

Gets all keys of the dictionary

 dic1.keys;
Copy the code

2.?? = and????

?? = : If the value of this variable is empty, it is assigned, otherwise it is not.

?? : Returns the left if there is a value on the left, otherwise returns the right.

3. Methods and arrow functions

The method in Dart is also an object, and the return value and parameter types can be omitted. The arrow function => can be used when the method’s execution statement is one sentence long.

void main() => functionDemo();
Copy the code

Normal function

int sum(int a, int b) {
  return a + b;
  }
Copy the code

Ignore the return value and parameter type

sum( a,  b) {
  return a + b;
  }
Copy the code

4. Optional parameters of the method

Optional arguments must be passed with the name of the parameter.

sum(int a,{ b, c}){ b ?? = 0; c ?? = 0; return a + b + c; }Copy the code

When this is called, it takes the name of the parameter. The order here can be reversed.

sum(1,c:2,b:3);
Copy the code

You can pass only one optional argument, or none at all.

sum(1,b:3);
sum(1);
Copy the code

If the function defines an optional argument to be of type Int,String, etc., do you need to add one after Int,String? , then there is null ability, the parameter can be null. But remember to deal with null arguments here.

sum(int a,{int? b,int? c}){ b ?? = 0; c ?? = 0; return a + b + c; }Copy the code

Or you can give the parameter a default value.

sum(int a,{int b = 0,int c = 0}){
  return a + b + c;
}
Copy the code

There is another method that does not need to pass the names of the parameters, but simply enter the values in order. There is no way to skip b and assign to C. If you enter only two arguments, then a and b will be assigned.

sum(int a,[int b = 0, int c = 0]){
  return a + b + c;
}
Copy the code

call

The sum (1, 2, 3); The sum (1, 2);Copy the code