What does that 2 dots mean? What is the difference between 1 and 2?

后端 未结 2 422
情深已故
情深已故 2021-01-11 17:20

I have seen a lot of tutorials using dot, while some use 2. What is the actual meaning of this?

Example,

Array().add()

Animation()..addListener(() {         


        
相关标签:
2条回答
  • 2021-01-11 17:41

    The .. operator is dart "cascade" operator. Useful for chaining operations when you don't care about the return value. This is also dart solution to chainable functions that always return this

    It is made so that the following

    final foo = Foo()
     ..first()
     ..second();
    

    Is strictly equals to this:

    final foo = Foo();
    foo.first():
    foo.second();
    
    0 讨论(0)
  • 2021-01-11 17:41

    Just to be a nitpicker, .. isn't actually an operator in Dart, just part of Dart's syntactic sugar.

    In addition to the mentioned use of cascades for chaining calls to functions, you can also use it to access fields on the same object.

    Consider this code, taken from the Dart documentation:

    querySelector('#confirm') // Get an object.
      ..text = 'Confirm' // Use its members.
      ..classes.add('important')
      ..onClick.listen((e) => window.alert('Confirmed!'));
    

    The first method call, querySelector(), returns a selector object. The code that follows the cascade notation operates on this selector object, ignoring any subsequent values that might be returned.

    For more information about cascades, check out Dart's outstanding documentation!

    0 讨论(0)
提交回复
热议问题