【问题标题】:the meaning of the ( get ) keyword with Streams in flutterFlutter 中 (get) 关键字与 Streams 的含义
【发布时间】:2021-03-28 20:51:46
【问题描述】:
Sink<List<FoodItem>> get listSink => _listController.sink;

有人可以向我解释 (get) 是做什么的吗?

这是默认的接收器功能

【问题讨论】:

    标签: flutter stream


    【解决方案1】:

    这是 dart 中 getter 方法的语法。

    您有一个由_ 定义的私有参数。每个以下划线开头的变量都被认为是私有的,不能在类外读取。来自文档:

    与 Java 不同,Dart 没有关键字 public、protected 和 私人的。如果标识符以下划线 _ 开头,则它是私有的 它的图书馆。

    getter 语法类似于:

    Return type get myVarName => 你要返回的私有值

    想象一下这个非常简单的类:

    class A {
       int _n = 42;
       
       int get nValue => _n;
    }
    

    为了从 A 类访问 n 的值,我需要使用 getter,因为 n 是私有的。

    A myClass = A();
    
    A.n; // Error as n is private
    
    A.nValue; // Return 42.
    

    【讨论】:

      【解决方案2】:

      关键字get 表示dart 中的getter

      更具体地说,getter 是类接口的一部分,它允许您从类实例中检索特定值。在 Dart 中,您几乎可以将其视为不带参数并使用类似于从类实例访问字段值(即属性)的语法的方法。

      例如,

      void main() {
        Item myItem = Item(initialCost: 1000);
            
        print(myItem.cost); // 2002
        
        myItem.cost = 100; // Error because there is no setter 'cost' 
      }
      
      class Item{
      
        int _privateCost;
        int initialCost;
        
        int get cost {
           return _privateCost * 2;
        };
      
        // constructor
        Item({this.initialCost}){
          _privateCost = initialCost + 1;
        }
       
      }
      

      【讨论】:

        【解决方案3】:

        添加到@Maxouille 的答案:

        如果您在 Java 中将属性设为公开,然后决定将其设为私有(因为您必须在 get/set 方法中添加一些额外的逻辑),调用语法会发生变化 - 例如而不是A.nValue++;,您将拥有A.setNValue(A.getNValue()++);。 这就是为什么 Java 中的约定是从一开始就将所有属性设为私有,并用 get/set 方法包装它们。这最终会产生一堆什么都不做的代码,但是“以防万一”。

        这种漂亮的语法使您能够使用 get/set 包装方法轻松地将公共属性转换为私有属性 - 无需更改调用代码。

        在上面的示例中 - 属性 nValue 可以作为一个简单的 int 属性开始。一旦您决定将其设为私有 - 您可以像上面的示例一样更改您的类:创建一个新的私有变量 _n 并将您的 nValue 转换为 get/set 属性:

        int get nValue => _n;
        set nValue(int newValue) => _n=newValue;
        

        您的调用代码仍将保持不变nValue++;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-20
          • 1970-01-01
          • 2015-08-03
          • 2021-04-22
          • 2017-07-20
          • 1970-01-01
          • 2012-04-04
          • 2012-09-08
          相关资源
          最近更新 更多