基本语法

    1. main() {
    2. String say(String from, String msg, [String device]) {
    3. var result = '$from says $msg';
    4. if (device != null) {
    5. result = '$result with a $device';
    6. }
    7. }
    8. say('Hello', 'World', 'HeiHei!!!');
    9. void enableFlags({bool bold, bool hidden}) {}
    10. enableFlags(bold: true, hidden: false);
    11. Future.delayed(new Duration(seconds: 2), () {
    12. throw AssertionError('Error');
    13. return 'hi wolrd';
    14. }).then((data) {
    15. print(data);
    16. }, onError: (e) {
    17. print(e);
    18. }).catchError((e) {
    19. print(e);
    20. }).whenComplete(() {
    21. print('compelete');
    22. });
    23. Future.wait([
    24. Future.delayed(new Duration(seconds: 2), () {
    25. return 'hellow';
    26. }),
    27. Future.delayed(new Duration(seconds: 3), () {
    28. return 'wolrd';
    29. })
    30. ]).then((results) {
    31. print(results[0] + results[1]);
    32. });
    33. // callback hell
    34. Future<String> login(String userName, String pwd) {
    35. // 用户登录
    36. String id = '11232';
    37. // return id;
    38. }
    39. Future<String> getUserInfo(String id) {
    40. // 获取用户信息
    41. }
    42. Future saveUserInfo(String userInfo) {
    43. // 保存用户信息
    44. }
    45. login('nardo', '*******').then((id) {
    46. getUserInfo(id).then((userInfo) {
    47. saveUserInfo(userInfo).then((res) {});
    48. });
    49. });
    50. task() async {
    51. try {
    52. String id = await login('nardo', '***');
    53. String userInfo = await getUserInfo(id);
    54. await saveUserInfo((userInfo));
    55. } catch (e) {
    56. print(e);
    57. }
    58. }
    59. // stream
    60. Stream.fromFutures([
    61. // 1s after
    62. Future.delayed(new Duration(seconds: 1), () {
    63. return 'hellow 1';
    64. }),
    65. // 2s after
    66. Future.delayed(new Duration(seconds: 2), () {
    67. throw AssertionError('error 1');
    68. }),
    69. // 3s after
    70. Future.delayed(new Duration(seconds: 3), () {
    71. return 'hellow 3';
    72. })
    73. ]).listen((data) {
    74. print(data);
    75. }, onError: (e) {
    76. print(e.message);
    77. }, onDone: (){
    78. });
    79. }

    思考:既然Stream可以接收多次事件,那能不能用Stream来实现一个订阅者模式的事件总线?