How do method cascades work exactly in dart?

前端 未结 3 404
夕颜
夕颜 2020-12-15 05:43

As stated in the dart article:

The \"..\" syntax invokes a method (or setter or getter) but discards the result, and returns the original receiver ins

3条回答
  •  情歌与酒
    2020-12-15 05:55

    As pointed in the official Dart language article Method Cascades in Dart:

    The ".." syntax invokes a method (or setter or getter) but discards the result, and returns the original receiver instead.

    In brief, method cascades provide a syntactic sugar for situations where the receiver of a method invocation might otherwise have to be repeated.

    Below are example based/copied from the previously cited article. For further information, go read it.

    add() example

    In the scenario where one want to add multiple elements to a list, the legacy-way is to do multiple assignements :

    myList.add("item1");
    myList.add("item2");
    // add again and again…
    myList.add("itemN");
    

    While you can't do something like myList.add("item1").add("item1")….add("itemN"); as the add() does not method return the myList object but a void, you can use the cascading operator instead as it discards the result, and returns the original receiver myList :

    myList..add("item1")..add("item2")…..add("itemN");
    
    myList.add("item1").add("item2")….add("itemN");
    

    Another example

    So Instead of writing:

    var address = getAddress();
    address.setStreet(“Elm”, “13a”);
    address.city = “Carthage”;
    address.state = “Eurasia”
    address.zip(66666, extended: 6666);
    

    One may write

    getAddress()
     ..setStreet(“Elm”, “13a”)
     ..city = “Carthage”
     ..state = “Eurasia”
     ..zip(66666, extended: 6666);
    

    Further reading

    If you want to know more about cascading method, I wrote an article by adding information that goes behind the scope of this question.

提交回复
热议问题