Notas de dardo

1 Ni la función ni el método de la clase en Dart admiten la sobrecarga, el nombre del método es el mismo y el parámetro es diferente, se informará un error.

class A{

  A(){

  }

  A(int a){
    //这个地方会报错,说A()函数已经存在
  }

  A.eat(){
      //构造函数
  }
  A.sing(int food){
      //构造函数
  }
  A.sleep(){
      //构造函数
  }

}

2 métodos Getter y Stter

class D{

 int num1,num2;

 // Getter方法 
 // int表示返回值类型,可以省略不写
 // get 声明是Get方法
 int get sum => num1+num2 ;

 // Setter方法 
 // setter方法不需要声明返回值类型
 // set 声明是Setter方法
set reduce(int num3) => num3-num2;

}

3 Comparación de final y constante

​
class D{

  final boa;
  
  // const声明的变量必须初始化,不初始化会报错;
  // final声明的变量可以不初始化, 但必须在构造函数体执行之前初始化
  // Const 变量是类级别的,需要标记为 static const,不声明static会报错
  static const String bob  = "bob";

    void initBofamily(){
      // 这个地方的Const 变量是方法里面,就不用必须声明static
      const boc = "boc";
      final bod = "bod";
    }

    D(int boaVaule):boa = boaVaule{
      //此处为D的构造函数,boa初始化为boaVaule
      //是在构造函数执行之前进行
    }
} 

​

Hay otra diferencia: las variables de instancia pueden ser finales pero no constantes

Primero mira qué es una variable de instancia

class Student{

   
  String name = "lucy";//实例变量
  static int age = 26; //静态变量,它是公有的
 

}
main(){

  Student studentA = new Student();
  studentA.name = "bob";
  Student.age = 32;
  print("studentA name: ${studentA.name} , age: ${Student.age}");

  Student studentB = new Student();
  print("studentB name: ${studentB.name} , age: ${Student.age}");

}

Resultado de la impresión:

La observación muestra que el alumnoA ha modificado el nombre y la edad. Ambos resultados impresos han sido modificados.

Sin embargo, studentB no modificó ningún dato, pero se imprimió que el nombre se inicializó de forma predeterminada y lucy no cambió, pero la edad no era el valor inicializado original.

Es el valor modificado de studentA.

El motivo es que el nombre es una variable de instancia. Siempre que aparezca un nuevo objeto Student, el nombre es el valor predeterminado de inicialización. El objeto studentA modifica el nombre, pero no funciona para studentB a menos que studentB lo modifique por sí mismo.

Después de que studentA modifique la variable de edad, studentB también se modifica.

 

Veamos esta oración nuevamente: las variables de instancia pueden ser finales pero no constantes

Es decir, el nombre del ejemplo anterior se puede modificar con final, pero no se puede modificar de nuevo, pero no se puede modificar con const.

Debido a que las variables de clase deben ser modificadas por const para agregar estática y agregar estática para convertirse en una variable constante y volverse lo mismo que age, ya no es una variable de instancia.

4 Dart parámetro opcional {......} forma y comparación [.....] forma

/**
   { ...  }形式
*/
class ContainerView{

  ContainerView({int key,String text,int color}){

       
  }

 ContainerView.requiredView({@required int key,String text,int color}){
      


  }
}
main(){

//调用时可选所以可以选择所传个数,但必须是 (参数名:参数值) 形式,例如:key: 234
//例1:可以不传任何参数
new ContainerView();

//例2:可以只传部分参数 
new ContainerView(key:1,text:"contentMsg");

//例3:参数位置可以不按顺序,位置可换因为调用时会用key:vaule的形式,所以位置不必对应 
new ContainerView(text:"contentMsg",key: 234);

//例4:如果只传值 不使用 参数名:参数值(例如:key: 234) 的形式 
//会报错
new ContainerView("contentMsg",234);

//例5:如果可选参数里面某个参数要必须传,可以用@required修饰
//此时调用必须传所修饰参数,否则报错
//而其他参数可选,
new ContainerView.requiredView(key: 1);//key:1  必须传

}
/**
      [ .... ] 形式
*/
class ContainerView{

  
  void sayMethod([String text,int time,bool isMan]){

  }
  void sayMethod2(String text,[int time,bool isMan]){

  }
}

main(){

   ContainerView containerView = new ContainerView();

  //例1:可以不传任何参数
  containerView.sayMethod();

  //例2:可以只传部分参数,但是必须按参数顺序传值
  //sayMethod 中顺序为 String int bool 
  //若 containerView.sayMethod("textVaule",false,2);就会报错
  //还有像sayMethod(参数1,参数2,参数3)有三个参数 
  //调用时可sayMethod(参数1,参数2)但sayMethod(参数2,参数3)忽略参数1会报错
  containerView.sayMethod("textVaule",2,false);

  //例3:参数放在[]外的参数为必须传的参数,否则报错
  containerView.sayMethod2("textRequired");

}//main()

para resumir:

{.......} Formulario:

El parámetro puede elegir si pasar el valor (excepto el parámetro modificado por @required);

Pero debe tener la forma de clave: vaule;

La posición puede estar fuera del orden de los parámetros

[.......] Forma:

El parámetro puede elegir si pasar el valor o no, pero debe estar en el orden de los parámetros, el parámetro anterior no se puede omitir y el último parámetro no se puede pasar.

No es necesario utilizar la forma de clave: vaule;

La posición debe seguir el orden de los parámetros, si hay varios parámetros

 

5 Cómo elegir el mapa transversal de la colección () y forEach ()

//map() 是带有返回值的,返回一个Iterable<T>类型

/**
   * Returns a new lazy [Iterable] with elements that are created by
   * calling `f` on each element of this `Iterable` in iteration order.
   *
   * This method returns a view of the mapped elements. As long as the
   * returned [Iterable] is not iterated over, the supplied function [f] will
   * not be invoked. The transformed elements will not be cached. Iterating
   * multiple times over the returned [Iterable] will invoke the supplied
   * function [f] multiple times on the same element.
   *
   * Methods on the returned iterable are allowed to omit calling `f`
   * on any element where the result isn't needed.
   * For example, [elementAt] may call `f` only once.
   */
Iterable<T> map<T>(T f(E e)) => MappedIterable<E, T>(this, f);

//forEach()是不带返回值的
/**
   * Applies the function [f] to each element of this collection in iteration
   * order.
   */
  void forEach(void f(E element)) {
    for (E element in this) f(element);
  }

 

Supongo que te gusta

Origin blog.csdn.net/u011288271/article/details/106053802
Recomendado
Clasificación