File size: 37,676 Bytes
08c8a6d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 |
dart #dart Table of Contents About Chapter 1: Getting started with dart Remarks Links Documentation FAQ Versions Examples Installation or Setup Automated installation and updates Manual install Hello, World! Http Request Html Dart Example Getters and Setters Chapter 2: Asynchronous Programming Examples Returning a Future using a Completer Async and Await Converting callbacks to Futures Chapter 3: Classes Examples Creating a class Members Constructors Chapter 4: Collections Examples Creating a new List 1 2 2 2 2 3 3 5 5 5 5 5 6 6 6 6 6 8 8 8 8 9 10 10 10 10 11 13 13 13 Creating a new Set Creating a new Map Map each element in the collection. Filter a list Chapter 5: Comments Syntax Remarks Examples End of Line Comment Multi-Line Comment Documentation using Dartdoc Chapter 6: Control Flow Examples If Else While Loop For Loop Switch Case Chapter 7: Converting Data Examples JSON Chapter 8: Dart-JavaScript interoperability Introduction Examples Calling a global function Wrapping JavaScript classes/namespaces Passing object literals Chapter 9: Date and time Examples Basic usage of DateTime Chapter 10: Enums Examples Basic usage 13 13 14 14 16 16 16 16 16 16 16 18 18 18 18 19 19 21 21 21 22 22 22 22 22 23 24 24 24 25 25 25 Chapter 11: Exceptions Remarks Examples Custom exception Chapter 12: Functions Remarks Examples Functions with named parameters Function scoping Chapter 13: Libraries Remarks Examples Using libraries Libraries and visibility Specifying a library prefix Importing only part of a library Lazily loading a library Chapter 14: List Filters Introduction Examples Filtering a list of integers Chapter 15: Pub Remarks Examples pub build pub serve Chapter 16: Regular Expressions Syntax Parameters Remarks Examples 26 26 26 26 27 27 27 27 27 29 29 29 29 29 30 30 30 32 32 32 32 33 33 33 33 33 34 34 34 34 34 Create and use a Regular Expression Chapter 17: Strings Examples Concatenation and interpolation Valid strings Building from parts Credits 34 35 35 35 35 35 37 About You can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: dart It is an unofficial and free dart ebook created for educational purposes. All the content is extracted from Stack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official dart. The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified. All trademarks and registered trademarks are the property of their respective company owners. Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to [email protected] https://riptutorial.com/ 1 Chapter 1: Getting started with dart Remarks Dart is an open-source, class-based, optionally-typed programming language for building web applications--on both the client and server--created by Google. Dart’s design goals are: • • • Create a structured yet flexible language for web programming. Make Dart feel familiar and natural to programmers and thus easy to learn. Ensure that Dart delivers high performance on all modern web browsers and environments ranging from small handheld devices to server-side execution. Dart targets a wide range of development scenarios, from a one-person project without much structure to a large-scale project needing formal types in the code to state programmer intent. To support this wide range of projects, Dart provides the following features and tools: • • • • • Optional types: this means you can start coding without types and add them later as needed. Isolates: concurrent programming on server and client Easy DOM access: using CSS selectors (the same way that jQuery does it) Dart IDE Tools: Dart plugins exist for many commonly used IDEs, Ex: WebStorm. Dartium: a build of the Chromium Web Browser with a built-in Dart Virtual Machine Links • • • • • • • The Dart Homepage Official Dart News & Updates The Dartosphere - A collection of recent Dart blog posts Dartisans Dartisans community on Google+ Dart Web Development - Google Groups Page Dart Language Misc - Google Groups Page DartLang sub-Reddit Documentation • • • • Tour of the Dart Language Tour of the Dart Libraries Dart Code samples Dart API Reference https://riptutorial.com/ 2 FAQ • Frequently Asked Questions Versions Version Release Date 1.22.1 1.22.0 1.21.1 1.21.0 1.20.1 1.20.0 1.19.1 1.19.0 1.18.1 1.18.0 1.17.1 1.17.0 1.16.1 1.16.0 1.15.0 1.14.2 1.14.1 1.14.0 1.13.2 1.13.1 1.13.0 2017-02-22 2017-02-14 2016-01-13 2016-12-07 2016-10-13 2016-10-11 2016-09-07 2016-08-26 2016-08-02 2016-07-27 2016-06-10 2016-06-06 2016-05-23 2016-04-26 2016-03-09 2016-02-09 2016-02-03 2016-01-28 2016-01-05 2015-12-17 2015-11-18 https://riptutorial.com/ 3 Version Release Date 1.12.2 1.12.1 1.12.0 1.11.3 1.11.1 1.11.0 1.10.1 1.10.0 1.9.3 1.9.1 1.8.5 1.8.3 1.8.0 1.7.2 1.6.0 1.5.8 1.5.3 1.5.2 1.5.1 1.4.3 1.4.2 1.4.0 1.3.6 1.3.3 1.3.0 2015-10-21 2015-09-08 2015-08-31 2015-08-03 2015-07-02 2015-06-24 2015-05-11 2015-04-24 2015-04-13 2015-03-25 2015-01-13 2014-12-01 2014-11-27 2014-10-14 2014-08-27 2014-07-29 2014-07-03 2014-07-02 2014-06-24 2014-06-16 2014-05-27 2014-05-20 2014-04-30 2014-04-16 2014-04-08 https://riptutorial.com/ 4 Version Release Date 1.2.0 1.1.3 1.1.1 2014-02-25 2014-02-06 2014-01-15 1.0.0.10_r30798 2013-12-02 1.0.0.3_r30188 2013-11-12 0.8.10.10_r30107 2013-11-08 0.8.10.6_r30036 2013-11-07 0.8.10.3_r29803 2013-11-04 Examples Installation or Setup The Dart SDK includes everything you need to write and run Dart code: VM, libraries, analyzer, package manager, doc generator, formatter, debugger, and more. If you are doing web development, you will also need Dartium. Automated installation and updates • • • Installing Dart on Windows Installing Dart on Mac Installing Dart on Linux Manual install You can also manually install any version of the SDK. Hello, World! Create a new file named hello_world.dart with the following content: void main() { print('Hello, World!'); } In the terminal, navigate to the directory containing the file hello_world.dart and type the following: dart hello_world.dart https://riptutorial.com/ 5 Hit enter to display Hello, World! in the terminal window. Http Request Html <img id="cats"></img> Dart import 'dart:html'; /// Stores the image in [blob] in the [ImageElement] of the given [selector]. void setImage(selector, blob) { FileReader reader = new FileReader(); reader.onLoad.listen((fe) { ImageElement image = document.querySelector(selector); image.src = reader.result; }); reader.readAsDataUrl(blob); } main() async { var url = "https://upload.wikimedia.org/wikipedia/commons/2/28/Tortoiseshell_she-cat.JPG"; // Initiates a request and asynchronously waits for the result. var request = await HttpRequest.request(url, responseType: 'blob'); var blob = request.response; setImage("#cats", blob); } Example see Example on https://dartpad.dartlang.org/a0e092983f63a40b0b716989cac6969a Getters and Setters void main() { var cat = new Cat(); print("Is cat hungry? ${cat.isHungry}"); // Is cat hungry? true print("Is cat cuddly? ${cat.isCuddly}"); // Is cat cuddly? false print("Feed cat."); cat.isHungry = false; print("Is cat hungry? ${cat.isHungry}"); // Is cat hungry? false print("Is cat cuddly? ${cat.isCuddly}"); // Is cat cuddly? true } class Cat { bool _isHungry = true; bool get isCuddly => !_isHungry; https://riptutorial.com/ 6 bool get isHungry => _isHungry; bool set isHungry(bool hungry) => this._isHungry = hungry; } Dart class getters and setters allow APIs to encapsulate object state changes. See dartpad example here: https://dartpad.dartlang.org/c25af60ca18a192b84af6990f3313233 Read Getting started with dart online: https://riptutorial.com/dart/topic/843/getting-started-with-dart https://riptutorial.com/ 7 Chapter 2: Asynchronous Programming Examples Returning a Future using a Completer Future<Results> costlyQuery() { var completer = new Completer(); database.query("SELECT * FROM giant_table", (results) { // when complete completer.complete(results); }, (error) { completer.completeException(error); }); // this returns essentially immediately, // before query is finished return completer.future; } Async and Await import 'dart:async'; Future main() async { var value = await _waitForValue(); print("Here is the value: $value"); //since _waitForValue() returns immediately if you un it without await you won't get the result var errorValue = "not finished yet"; _waitForValue(); print("Here is the error value: $value");// not finished yet } Future<int> _waitForValue() => new Future((){ var n = 100000000; // Do some long process for (var i = 1; i <= n; i++) { // Print out progress: if ([n / 2, n / 4, n / 10, n / 20].contains(i)) { print("Not done yet..."); } // Return value when done. if (i == n) { print("Done."); return i; } } }); https://riptutorial.com/ 8 See example on Dartpad: https://dartpad.dartlang.org/11d189b51e0f2680793ab3e16e53613c Converting callbacks to Futures Dart has a robust async library, with Future, Stream, and more. However, sometimes you might run into an asynchronous API that uses callbacks instead of Futures. To bridge the gap between callbacks and Futures, Dart offers the Completer class. You can use a Completer to convert a callback into a Future. Completers are great for bridging a callback-based API with a Future-based API. For example, suppose your database driver doesn't use Futures, but you need to return a Future. Try this code: // A good use of a Completer. Future doStuff() { Completer completer = new Completer(); runDatabaseQuery(sql, (results) { completer.complete(results); }); return completer.future; } If you are using an API that already returns a Future, you do not need to use a Completer. Read Asynchronous Programming online: https://riptutorial.com/dart/topic/2520/asynchronous- programming https://riptutorial.com/ 9 Chapter 3: Classes Examples Creating a class Classes can be created as follow: class InputField { int maxLength; String name; } The class can be instantiated using the new keyword after which the field values will be null by default. var field = new InputField(); Field values can then be accessed: // this will trigger the setter field.name = "fieldname"; // this will trigger the getter print(field.name); Members A class can have members. Instance variables can be declared with/without type annotations, and optionally initialized. Uninitialised members have the value of null, unless set to another value by the constructor. class Foo { var member1; int member2; String member3 = "Hello world!"; } Class variables are declared using the static keyword. class Bar { static var member4; static String member5; static int member6 = 42; } If a method takes no arguments, is fast, returns a value, and doesn't have visible side-effects, then https://riptutorial.com/ 10 a getter method can be used: class Foo { String get bar { var result; // ... return result; } } Getters never take arguments, so the parentheses for the (empty) parameter list are omitted both for declaring getters, as above, and for calling them, like so: main() { var foo = new Foo(); print(foo.bar); // prints "bar" } There are also setter methods, which must take exactly one argument: class Foo { String _bar; String get bar => _bar; void set bar(String value) { _bar = value; } } The syntax for calling a setter is the same as variable assignment: main() { var foo = new Foo(); foo.bar = "this is calling a setter method"; } Constructors A class constructor must have the same name as its class. Let's create a constructor for a class Person: class Person { String name; String gender; int age; Person(this.name, this.gender, this.age); } The example above is a simpler, better way of defining the constructor than the following way, which is also possible: https://riptutorial.com/ 11 class Person { String name; String gender; int age; Person(String name, String gender, int age) { this.name = name; this.gender = gender; this.age = age; } } Now you can create an instance of Person like this: var alice = new Person('Alice', 'female', 21); Read Classes online: https://riptutorial.com/dart/topic/1511/classes https://riptutorial.com/ 12 Chapter 4: Collections Examples Creating a new List Lists can be created in multiple ways. The recommended way is to use a List literal: var vegetables = ['broccoli', 'cabbage']; The List constructor can be used as well: var fruits = new List(); If you prefer stronger typing, you can also supply a type parameter in one of the following ways: var fruits = <String>['apples', 'oranges']; var fruits = new List<String>(); For creating a small growable list, either empty or containing some known initial values, the literal form is preferred. There are specialized constructors for other kinds of lists: var fixedLengthList1 = new List(8); var fixedLengthList2 = new List.filled(8, "initial text"); var computedValues = new List.generate(8, (n) => "x" * n); var fromIterable = new List<String>.from(computedValues.getRange(2, 5)); See also the Effective Dart style guide about collections. Creating a new Set Sets can be created via the constructor: var ingredients = new Set(); ingredients.addAll(['gold', 'titanium', 'xenon']); Creating a new Map Maps can be created in multiple ways. Using the constructor, you can create a new map as follow: var searchTerms = new Map(); https://riptutorial.com/ 13 Types for the key and value can also be defined using generics: var nobleGases = new Map<int, String>(); var nobleGases = <int, String>{}; Maps can otherwise be created using the map literal: var map = { "key1": "value1", "key2": "value2" }; Map each element in the collection. All collection objects contain a map method that takes a Function as an argument, which must take a single argument. This returns an Iterable backed by the collection. When the Iterable is iterated, each step calls the function with a new element of the collection, and the result of the call becomes the next element of the iteration. You can turn an Iterable into a collection again by using the Iterable.toSet() or Iterable.toList() methods, or by using a collection constructor which takes an iterable like Queue.from or List.from. Example: main() { var cats = [ 'Abyssinian', 'Scottish Fold', 'Domestic Shorthair' ]; print(cats); // [Abyssinian, Scottish Fold, Domestic Shorthair] var catsInReverse = cats.map((String cat) { return new String.fromCharCodes(cat.codeUnits.reversed); }) .toList(); // [nainissybA, dloF hsittocS, riahtrohS citsemoD] print(catsInReverse); } See dartpad example here: https://dartpad.dartlang.org/a18367ff767f172b34ff03c7008a6fa1 Filter a list Dart allows to easily filter a list using where. var fruits = ['apples', 'oranges', 'bananas']; fruits.where((f) => f.startsWith('a')).toList(); //apples Of course you can use some AND or OR operators in your where clause. https://riptutorial.com/ 14 Read Collections online: https://riptutorial.com/dart/topic/859/collections https://riptutorial.com/ 15 Chapter 5: Comments Syntax • • • // Single-line comment /* Multi-line/In-line comment */ /// Dartdoc comment Remarks It is good practice to add comments to your code to explain why something is done or to explain what something does. This helps any future readers of your code to more easily understand your code. Related topic(s) not on StackOverflow: • Effective Dart: Documentation Examples End of Line Comment Everything to the right of // in the same line is commented. int i = 0; // Commented out text Multi-Line Comment Everything between /* and */ is commented. void main() { for (int i = 0; i < 5; i++) { /* This is commented, and will not affect code */ print('hello ${i + 1}'); } } Documentation using Dartdoc Using a doc comment instead of a regular comment enables dartdoc to find it and generate documentation for it. /// The number of characters in this chunk when unsplit. int get length => ... https://riptutorial.com/ 16 You are allowed to use most markdown formatting in your doc comments and dartdoc will process it accordingly using the markdown package. /// This is a paragraph of regular text. /// /// This sentence has *two* _emphasized_ words (i.e. italics) and **two** /// __strong__ ones (bold). /// /// A blank line creates another separate paragraph. It has some `inline code` /// delimited using backticks. /// /// * Unordered lists. /// * Look like ASCII bullet lists. /// * You can also use `-` or `+`. /// /// Links can be: /// /// * http://www.just-a-bare-url.com /// * [with the URL inline](http://google.com) /// * [or separated out][ref link] /// /// [ref link]: http://google.com /// /// # A Header /// /// ## A subheader Read Comments online: https://riptutorial.com/dart/topic/2436/comments https://riptutorial.com/ 17 Chapter 6: Control Flow Examples If Else Dart has If Else: if (year >= 2001) { print('21st century'); } else if (year >= 1901) { print('20th century'); } else { print('We Must Go Back!'); } Dart also has a ternary if operator: var foo = true; print(foo ? 'Foo' : 'Bar'); // Displays "Foo". While Loop While loops and do while loops are allowed in Dart: while(peopleAreClapping()) { playSongs(); } and: do { processRequest(); } while(stillRunning()); Loops can be terminated using a break: while (true) { if (shutDownRequested()) break; processIncomingRequests(); } You can skip iterations in a loop using continue: for (var i = 0; i < bigNumber; i++) { if (i.isEven){ continue; } doSomething(); https://riptutorial.com/ 18 } For Loop Two types of for loops are allowed: for (int month = 1; month <= 12; month++) { print(month); } and: for (var object in flybyObjects) { print(object); } The for-in loop is convenient when simply iterating over an Iterable collection. There is also a forEach method that you can call on Iterable objects that behaves like for-in: flybyObjects.forEach((object) => print(object)); or, more concisely: flybyObjects.forEach(print); Switch Case Dart has a switch case which can be used instead of long if-else statements: var command = 'OPEN'; switch (command) { case 'CLOSED': executeClosed(); break; case 'OPEN': executeOpen(); break; case 'APPROVED': executeApproved(); break; case 'UNSURE': // missing break statement means this case will fall through // to the next statement, in this case the default case default: executeUnknown(); } You can only compare integer, string, or compile-time constants. The compared objects must be instances of the same class (and not of any of its subtypes), and the class must not override ==. https://riptutorial.com/ 19 One surprising aspect of switch in Dart is that non-empty case clauses must end with break, or less commonly, continue, throw, or return. That is, non-empty case clauses cannot fall through. You must explicitly end a non-empty case clause, usually with a break. You will get a static warning if you omit break, continue, throw, or return, and the code will error at that location at runtime. var command = 'OPEN'; switch (command) { case 'OPEN': executeOpen(); // ERROR: Missing break causes an exception to be thrown!! case 'CLOSED': // Empty case falls through case 'LOCKED': executeClosed(); break; } If you want fall-through in a non-empty case, you can use continue and a label: var command = 'OPEN'; switch (command) { case 'OPEN': executeOpen(); continue locked; locked: case 'LOCKED': executeClosed(); break; } Read Control Flow online: https://riptutorial.com/dart/topic/923/control-flow https://riptutorial.com/ 20 Chapter 7: Converting Data Examples JSON import 'dart:convert'; void main() { var jsonString = """ { "cats": { "abysinnian": { "origin": "Burma", "behavior": "playful" } } } """; var obj = JSON.decode(jsonString); print(obj['cats']['abysinnian']['behavior']); // playful } See example on dartpad: https://dartpad.dartlang.org/7d5958cf10e611b36326f27b062108fe Read Converting Data online: https://riptutorial.com/dart/topic/2778/converting-data https://riptutorial.com/ 21 Chapter 8: Dart-JavaScript interoperability Introduction Dart-JavaScript interoperability lets us run JavaScript code from our Dart programs. The interoperability is achieved by using the js library to create Dart stubs. These stubs describe the interface we'd like to have with the underlying JavaScript code. At runtime calling the Dart stub will invoke the JavaScript code. Examples Calling a global function Suppose we'd like to invoke the JavaScript function JSON.stringify which receives an object, encodes it into a JSON string and returns it. All we'd have to do is write the function signature, mark it as external and annotate it with the @JS annotation: @JS("JSON.stringify") external String stringify(obj); The @JS annotation will be used from here on out to mark Dart classes that we'd like to use in JavaScript as well. Wrapping JavaScript classes/namespaces Suppose we'd like to wrap the Google Maps JavaScript API google.maps: @JS('google.maps') library maps; import "package:js/js.dart"; @JS() class Map { external Map(Location location); external Location getLocation(); } We now have the Map Dart class which corresponds to the JavaScript google.maps.Map class. Running new Map(someLocation) in Dart will invoke new google.maps.Map(location) in JavaScript. Note that you don't have to name your Dart class the same as the JavaScript class: @JS("LatLng") https://riptutorial.com/ 22 class Location { external Location(num lat, num lng); } The Location Dart class corresponds to the google.maps.LatLng class. Using inconsistent names is discouraged as they can create confusion. Passing object literals It's common practice in JavaScript to pass object literals to functions: // JavaScript printOptions({responsive: true}); Unfortunately we cannot pass Dart Map objects to JavaScript in these cases. What we have to do is create a Dart object that represents the object literal and contains all of its fields: // Dart @JS() @anonymous class Options { external bool get responsive; external factory Options({bool responsive}); } Note that the Options Dart class doesn't correspond to any JavaScript class. As such we must mark it with the @anonymous annotation. Now we can create a stub for the original printOptions function and call it with a new Options object: // Dart @JS() external printOptions(Options options); printOptions(new Options(responsive: true)); Read Dart-JavaScript interoperability online: https://riptutorial.com/dart/topic/9240/dart-javascript- interoperability https://riptutorial.com/ 23 Chapter 9: Date and time Examples Basic usage of DateTime DateTime now = new DateTime.now(); DateTime berlinWallFell = new DateTime(1989, 11, 9); DateTime moonLanding = DateTime.parse("1969-07-20 20:18:00"); // 8:18pm You can find more in depth information here. Read Date and time online: https://riptutorial.com/dart/topic/3322/date-and-time https://riptutorial.com/ 24 Chapter 10: Enums Examples Basic usage enum Fruit { apple, banana } main() { var a = Fruit.apple; switch (a) { case Fruit.apple: print('it is an apple'); break; } // get all the values of the enums for (List<Fruit> value in Fruit.values) { print(value); } // get the second value print(Fruit.values[1]); } Read Enums online: https://riptutorial.com/dart/topic/5107/enums https://riptutorial.com/ 25 Chapter 11: Exceptions Remarks Dart code can throw and catch exceptions. Exceptions are errors indicating that something unexpected happened. If the exception isn’t caught, the isolate that raised the exception is suspended, and typically the isolate and its program are terminated. In contrast to Java, all of Dart’s exceptions are unchecked exceptions. Methods do not declare which exceptions they might throw, and you are not required to catch any exceptions. Dart provides Exception and Error types, as well as numerous predefined subtypes. You can, of course, define your own exceptions. However, Dart programs can throw any non-null object—not just Exception and Error objects—as an exception. Examples Custom exception class CustomException implements Exception { String cause; CustomException(this.cause); } void main() { try { throwException(); } on CustomException { print("custom exception is been obtained"); } } throwException() { throw new CustomException('This is my first custom exception'); } Read Exceptions online: https://riptutorial.com/dart/topic/3334/exceptions https://riptutorial.com/ 26 Chapter 12: Functions Remarks Dart is a true object-oriented language, so even functions are objects and have a type, Function. This means that functions can be assigned to variables or passed as arguments to other functions. You can also call an instance of a Dart class as if it were a function. Examples Functions with named parameters When defining a function, use {param1, param2, …} to specify named parameters: void enableFlags({bool bold, bool hidden}) { // ... } When calling a function, you can specify named parameters using paramName: value enableFlags(bold: true, hidden: false); Function scoping Dart functions may also be declared anonymously or nested. For example, to create a nested function, just open a new function block within an existing function block void outerFunction() { bool innerFunction() { /// Does stuff } } The function innerFunction may now be used inside, and only inside, outerFunction. No other other functions has access to it. Functions in Dart may also be declared anonymously, which is commonly used as function arguments. A common example is the sort method of List object. This method takes an optional argument with the following signature: int compare(E a, E b) The documentation states that the function must return 0 if the a and b are equal. It returns -1 if a < b and 1 if a > b. https://riptutorial.com/ 27 Knowing this, we can sort a list of integers using an anonymous function. List<int> numbers = [4,1,3,5,7]; numbers.sort((int a, int b) { if(a == b) { return 0; } else if (a < b) { return -1; } else { return 1; } }); Anonymous function may also be bound to identifiers like so: Function intSorter = (int a, int b) { if(a == b) { return 0; } else if (a < b) { return -1; } else { return 1; } } and used as an ordinary variable. numbers.sort(intSorter); Read Functions online: https://riptutorial.com/dart/topic/2965/functions https://riptutorial.com/ 28 Chapter 13: Libraries Remarks The import and library directives can help you create a modular and shareable code base. Every Dart app is a library, even if it doesn’t use a library directive. Libraries can be distributed using packages. See Pub Package and Asset Manager for information about pub, a package manager included in the SDK. Examples Using libraries Use import to specify how a namespace from one library is used in the scope of another library. import 'dart:html'; The only required argument to import is a URI specifying the library. For built-in libraries, the URI has the special dart: scheme. For other libraries, you can use a file system path or the package: scheme. The package: scheme specifies libraries provided by a package manager such as the pub tool. For example: import 'dart:io'; import 'package:mylib/mylib.dart'; import 'package:utils/utils.dart'; Libraries and visibility Unlike Java, Dart doesn’t have the keywords public, protected, and private. If an identifier starts with an underscore _, it’s private to its library. If you for example have class A in a separate library file (eg, other.dart), such as: library other; class A { int _private = 0; testA() { print('int value: $_private'); // 0 _private = 5; print('int value: $_private'); // 5 } } and then import it into your main app, such as: https://riptutorial.com/ 29 import 'other.dart'; void main() { var b = new B(); b.testB(); } class B extends A { String _private; testB() { _private = 'Hello'; print('String value: $_private'); // Hello testA(); print('String value: $_private'); // Hello } } You get the expected output: String value: Hello int value: 0 int value: 5 String value: Hello Specifying a library prefix If you import two libraries that have conflicting identifiers, then you can specify a prefix for one or both libraries. For example, if library1 and library2 both have an Element class, then you might have code like this: import 'package:lib1/lib1.dart'; import 'package:lib2/lib2.dart' as lib2; // ... var element1 = new Element(); // Uses Element from lib1. var element2 = new lib2.Element(); // Uses Element from lib2. Importing only part of a library If you want to use only part of a library, you can selectively import the library. For example: // Import only foo and bar. import 'package:lib1/lib1.dart' show foo, bar; // Import all names EXCEPT foo. import 'package:lib2/lib2.dart' hide foo; Lazily loading a library Deferred loading (also called lazy loading) allows an application to load a library on demand, if and when it’s needed. To lazily load a library, you must first import it using deferred as. https://riptutorial.com/ 30 import 'package:deferred/hello.dart' deferred as hello; When you need the library, invoke loadLibrary() using the library’s identifier. greet() async { await hello.loadLibrary(); hello.printGreeting(); } In the preceding code, the await keyword pauses execution until the library is loaded. For more information about async and await, see more examples here asynchrony support or visit the asynchrony support part of the language tour. Read Libraries online: https://riptutorial.com/dart/topic/3332/libraries https://riptutorial.com/ 31 Chapter 14: List Filters Introduction Dart filters lists through the List.where and List.retainWhere methods. The where function takes one argument: a boolean function that is applied to each element of the list. If the function evaluates to true then the list element is retained; if the function evaluates to false, the element is removed. Calling theList.retainWhere(foo) is practically equivalent to setting theList = theList.where(foo). Examples Filtering a list of integers [-1, 0, 2, 4, 7, 9].where((x) => x > 2) --> [4, 7, 9] Read List Filters online: https://riptutorial.com/dart/topic/10948/list-filters https://riptutorial.com/ 32 Chapter 15: Pub Remarks When you install the Dart SDK, one of the tools that you get is pub. The pub tool provides commands for a variety of purposes. One command installs packages, another starts up an HTTP server for testing, another prepares your app for deployment, and another publishes your package to pub.dartlang.org. You can access the pub commands either through an IDE, such as WebStorm, or at the command line. For an overview of these commands, see Pub Commands. Examples pub build Use pub build when you’re ready to deploy your web app. When you run pub build, it generates the assets for the current package and all of its dependencies, putting them into new directory named build. To use pub build, just run it in your package’s root directory. For example: $ cd ~/dart/helloworld $ pub build Building helloworld...... Built 5 files! pub serve This command starts up a development server, or dev server, for your Dart web app. The dev server is an HTTP server on localhost that serves up your web app’s assets. Start the dev server from the directory that contains your web app’s pubspec.yaml file: $ cd ~/dart/helloworld $ pub serve Serving helloworld on http://localhost:8080 Read Pub online: https://riptutorial.com/dart/topic/3335/pub https://riptutorial.com/ 33 Chapter 16: Regular Expressions Syntax • var regExp = RegExp(r'^(.*)$', multiLine: true, caseSensitive: false); Parameters Parameter Details String source The regular expression as a String {bool multiline} Whether this is a multiline regular expression. (matches ^ and $ at the beginning and end of each line individually not the whole String) {bool caseSensitive} If the expression is case sensitive Remarks Dart regular expressions have the same syntax and semantics as JavaScript regular expressions. See http://ecma-international.org/ecma-262/5.1/#sec-15.10 for the specification of JavaScript regular expressions. This means that any JavaScript resource you find about Regular Expressions online applies to dart. Examples Create and use a Regular Expression var regExp = new RegExp(r"(\w+)"); var str = "Parse my string"; Iterable<Match> matches = regExp.allMatches(str); It's a good idea to use "raw strings" (prefix with r) when writing regular expressions so you can use unescaped backslashes in your expression. Read Regular Expressions online: https://riptutorial.com/dart/topic/3624/regular-expressions https://riptutorial.com/ 34 Chapter 17: Strings Examples Concatenation and interpolation You can use the plus (+) operator to concatenate strings: 'Dart ' + 'is ' + 'fun!'; // 'Dart is fun!' You can also use adjacent string literals for concatenation: 'Dart ' 'is ' 'fun!'; // 'Dart is fun!' You can use ${} to interpolate the value of Dart expressions within strings. The curly braces can be omitted when evaluating identifiers: var text = 'dartlang'; '$text has ${text.length} letters'; // 'dartlang has 8 letters' Valid strings A string can be either single or multiline. Single line strings are written using matching single or double quotes, and multiline strings are written using triple quotes. The following are all valid Dart strings: 'Single quotes'; "Double quotes"; 'Double quotes in "single" quotes'; "Single quotes in 'double' quotes"; '''A multiline string'''; """ Another multiline string"""; Building from parts Programmatically generating a String is best accomplished with a StringBuffer. A StringBuffer doesn't generate a new String object until toString() is called. var sb = new StringBuffer(); sb.write("Use a StringBuffer"); https://riptutorial.com/ 35 sb.writeAll(["for ", "efficient ", "string ", "creation "]); sb.write("if you are ") sb.write("building lots of strings"); // or you can use method cascades: sb ..write("Use a StringBuffer") ..writeAll(["for ", "efficient ", "string ", "creation "]) ..write("if you are ") ..write("building lots of strings"); var fullString = sb.toString(); print(fullString); // Use a StringBufferfor efficient string creation if you are building lots of strings sb.clear(); // all gone! Read Strings online: https://riptutorial.com/dart/topic/5003/strings https://riptutorial.com/ 36 Credits S. No 1 2 3 4 5 6 7 8 9 Chapters Contributors Getting started with dart 4444, Challe, Community, Damon, Florian Loitsch, Gomiero, Kleak, losnake, martin, Raph, Timothy C. Quinn Asynchronous Programming Challe, Damon, Ray Hulha, Zied Hamdi Classes Ganymede, Hoylen, Jan Vladimir Mostert, Raph Collections Alexi Coard, Damon, Jan Vladimir Mostert, Kleak, lrn, Pacane, Raph Comments Challe Control Flow Ganymede, Jan Vladimir Mostert, Pacane, Raph Converting Data Damon Dart-JavaScript interoperability Date and time 10 Enums 11 Exceptions Meshulam Silk Challe Challe Challe 12 Functions Jan Vladimir Mostert, Kim Rostgaard Christensen 13 Libraries Challe, Ganymede 14 List Filters jxmorris12 15 Pub Challe 16 Regular Expressions enyo 17 Strings Challe https://riptutorial.com/ 37 |