└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # dart-cheat-sheet 2 | A curated list of awesome stuff needed to get started with your flutter development journey 3 | 4 | [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) ![Branch master](https://img.shields.io/badge/branch-master-brightgreen.svg?style=flat-square)[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/temidtech/dart-cheat-sheet/master/LICENSE) 5 | 6 | ## Table of Contents 7 | 8 | - [String interpolation](#string-interpolation) 9 | - [Functions](#functions) 10 | - [Parsing](#parsing) 11 | - [List Arrays](#list-arrays) 12 | - [Lambda Functions](#lambda-functions) 13 | - [Null-aware Operators](#null-aware-operators) 14 | - [Conditional Property Access](#conditional-property-access) 15 | - [Collections Literals](#collections-literals) 16 | - [Arrow Syntax](#arrow-syntax) 17 | - [Iterations](#iterations) 18 | - [Map](#map) 19 | - [Variables](#variables) 20 | - [Class](#class) 21 | - [Getters and Setters](#getters-and-setters) 22 | - [Futures: Async and Await](#future-async-await) 23 | - [JSON and serialization](#json-and-serialization) 24 | - [Reading and decoding a file](#Reading-and-decoding-a-file) 25 | - [Sound null safety](#sound-null-safety) 26 | 27 | 28 | 29 | ## String interpolation 30 | 31 | Every language has it's own way of interpolating two or more words or characters. In dart, you can put value of an expression inside a string as follows: 32 | 33 | ### Example 34 | 35 | ```dart 36 | int x=6; 37 | int y=2; 38 | String sum = '${x+y}'; // result is 8 39 | String subtraction = '${x-y}'; // result is 4 40 | String upperCase = '${"hello".toUpperCase()}'; // result is HELLO 41 | String concatXY = '$x$y'; // result is '62' 42 | ``` 43 | 44 | ## Functions 45 | Dart lang is an OOL(Object-oriented language), In this language, functions are objects and have a type, Function. This implies that functions can be assigned to 46 | variables or passed as args to other functions. Interestingly, you can also call an instance of a class as if it were a fuction. That's awesome, right? 47 | 48 | ### Example 49 | 50 | ```dart 51 | String fullName(){ 52 | String firstName = "Temidayo"; 53 | String lastName = "Adefioye"; 54 | return '$firstName $lastName'; // returns 'Temidayo Adefioye' 55 | } 56 | ``` 57 | 58 | ```dart 59 | int length(String text){ 60 | return text.length; // returns length of text 61 | } 62 | ``` 63 | 64 | The above function can be rewritten in a more concise way: 65 | 66 | ```dart 67 | int length(String text) => return text.length; // returns length of text 68 | ``` 69 | 70 | The above approach is applicable where functions contain just ONE expression. This is also referred to as shorthand syntax. 71 | 72 | ## Parsing 73 | 74 | Parsing a string to a number such as integer and double is very key. As a developer, often times I need to convert(parse) a string value 75 | coming from a server-side to a number, tryParse method comes in handy. Take a look at this code snippet: 76 | 77 | ### Example 78 | 79 | ```dart 80 | var a = "121"; 81 | var b = "120.56"; 82 | var c = "100.a12"; 83 | var d = "abc"; 84 | String parseA = int.tryParse(a); // result is 121 85 | String parseB = double.tryParse(b); // result is 120.56 86 | String parseC = double.tryParse(c); // result is null (that string contains invalid number) 87 | String parseD = double.tryParse(d); // result is null (that string contains invalid number) 88 | ``` 89 | 90 | ## List Arrays 91 | 92 | Perhaps the most common collection in nearly every programming language is the array or ordered set of objects. Please note that Dart arrays are Lists. 93 | 94 | ### Example 95 | 96 | ```dart 97 | var numList = [1,2,3,5,6,7]; 98 | var countryList = ["Nigeria","United States","United Kingdom","Ghana","IreLand","Germany"]; 99 | String numLength = numList.length; // result is 6 100 | String countryLength = countryList.length; // result is 6 101 | String countryIndex = countryList[1]; // result is 'United States' 102 | String numIndex = numList[0]; // result is 1 103 | 104 | countryList.add("Poland"); // Adds a new item to the list. 105 | 106 | var emailList = new List(3); // Set a fixed list size 107 | var emailList = new List(); // instance of a list of type String 108 | 109 | ``` 110 | 111 | ## Lambda Functions 112 | 113 | Lambda functions provide you with a short and concise way of representing small functions. They are also referred to as Arrow functions. In dart, if you need to write quick throw away functions without necessarily naming them, lambda fucntion is all you need. With the power of this function you can do the following and more: 114 | 115 | ### Example 116 | 117 | ```dart 118 | var numList = new List.generate(5,(i) => i); 119 | print(numList); //result: {0,1,2,3,4} 120 | var loans = numList.map( (n) => "\#$n").toList(); 121 | print(loans); // result: {#0, #1, #3, #4} 122 | 123 | printMsg()=> print("Hello world"); 124 | 125 | // You can declare a state function this way in flutter 126 | _DashboardState createState() => _DashboardState(); 127 | 128 | // How about creating a widget using lambda? 129 | Card makeCard(Asset assetViewModel) => Card( 130 | elevation: 8.0, 131 | margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0), 132 | child: Container( 133 | decoration: BoxDecoration(color: Colors.white), 134 | child: makeListTile(assetViewModel), // where makeListTile is a custom widget created already 135 | ), 136 | ); 137 | 138 | 139 | ``` 140 | 141 | ## Null-aware Operators 142 | 143 | Handling null exceptions in app development is very essential, as this allows you to create a seamless experience for your app users. Dart provides you with some handy operators for dealing with values that might be null. One is the ??= assignment operator, which assigns a value of a variable only if that variable is currently null: 144 | 145 | ### Example 146 | 147 | ```dart 148 | int x; // The initial value of any object is null 149 | x ??=6; 150 | print(x); // result: 6 151 | 152 | x ??=3; 153 | print(x); // result is still 6 154 | 155 | print(null ?? 10); // result: 10. Display the value on the left if it's not null else return the value on the right 156 | 157 | ``` 158 | 159 | 160 | ## Conditional Property Access 161 | 162 | To properly safegaurd access to a property or method of an object that might be null, put a question mark (?) before the (.) 163 | 164 | ### Example 165 | 166 | ```dart 167 | 168 | userObject?.userName 169 | 170 | //The code snippet above is equivalent to following: 171 | 172 | (userObject !=null) ? userObject.userName : null 173 | 174 | //You can chain multiple uses of ?. together in a single expression 175 | 176 | userObject?.userName?.toString() 177 | 178 | // The preceeding code returns null and never calls toString() if either userObject or userObject.userName is null 179 | 180 | ``` 181 | 182 | ## Collections Literals 183 | 184 | With literals you can create Dart's built-in lists, maps and sets without hassle. 185 | 186 | ### Example 187 | 188 | ```dart 189 | 190 | final fruitList = ["Orange","Bannana","Carrot","Apple"]; // A list of fruit 191 | final countrySet = {"Nigeria","United States","Poland","Italy"}; // A set of country 192 | final credMap = { 193 | 'userName': 'temi', 194 | 'password': 'xmen' 195 | } // A map of user credentials 196 | 197 | ``` 198 | 199 | You maybe wondering why we didn't explicitly declare a type for all of the collections above. It's interesting to know that dart's type inference can assign types to these variables for you. In this case, the inferred types are List, Set and Map. 200 | 201 | Please note that you can choose to specify a type for your variable declaration like this: 202 | 203 | ```dart 204 | 205 | final fruitList = []; 206 | final countrySet = {}; 207 | final credMap = {}; 208 | 209 | ``` 210 | 211 | ## Arrow Syntax 212 | 213 | Remember Lambda Functions as discussed earlier in this sheet? We used a symbol => to define our lambda expression. You can check out Lambda function section for more explanation. 214 | 215 | ### Example 216 | 217 | ```dart 218 | 219 | String _firstName = "Michael"; 220 | String _lastName = "Jones"; 221 | String _middleName = "Will"; 222 | 223 | String get fullName => '$_firstName $_middleName $_lastName'; // result: 'Michael Will Jones' 224 | 225 | 226 | ``` 227 | 228 | ## Iterations 229 | 230 | Just like every other programming language out there, you can perform iterations in dart. Here is a for loop example 231 | 232 | ### Example 233 | 234 | ```dart 235 | 236 | for (int i=0; i<=20; i++){ 237 | print(i); // prints 1 to 20 238 | } 239 | 240 | var fruitList = ["Orange","Bannana","Carrot","Apple"]; 241 | for (final fruit in fruits){ 242 | print(fruit); // prints all types of fruit in the list 243 | } 244 | 245 | ``` 246 | 247 | ## Map 248 | 249 | Map can either be declared using literals or map constructor. To learn more about map declaration using literals, please go to the Collections Literals section. Here is how you can declare map using a map constructor: 250 | 251 | ### Example 252 | 253 | ```dart 254 | var user = new Map(); 255 | // To initialize the map, do this: 256 | user['firstName'] = 'Paul'; 257 | user['lastName'] = 'Pogba'; 258 | 259 | // Result: {firstName: Paul, lastName: Pogba} 260 | 261 | 262 | // Below are map properties 263 | 264 | - Keys 265 | - Values 266 | - Length 267 | - isEmpty 268 | - isNotEmpty 269 | 270 | // Below are map functions 271 | 272 | - addAll() 273 | - clear() 274 | - remove() 275 | - forEach() 276 | ``` 277 | 278 | ## Variables 279 | 280 | Here's an example of creating a variable and initializing it: 281 | 282 | ### Example 283 | 284 | ```dart 285 | int x = 2; // explicitly typed 286 | var p = 5; // type inferred 287 | p = "cool"; // ops! throws an error 288 | dynamic z = 8; // variable can take on any type 289 | z = "cool"; // cool 290 | 291 | // if you never intend to change a variable use final or const. Something like this: 292 | 293 | final email = "temid@gmail.com"; // you can't change the value 294 | final String email = "temid@gmail.com"; // you can't change the value 295 | 296 | // iPhone 11 Pro max calculator using const 297 | 298 | const qty = 5; 299 | const totalCost = 1099 * qty; 300 | 301 | ``` 302 | 303 | ## Class 304 | 305 | In Dart, the class keyword is used to declare a class. Here is a basic example: 306 | 307 | ### Example 308 | 309 | ```dart 310 | class Car { 311 | // field 312 | String engine = "E1001"; 313 | // function 314 | void disp() { 315 | print(engine); 316 | } 317 | } 318 | 319 | ``` 320 | 321 | ## Getters and Setters 322 | 323 | Getters and setters are special methods that provide read and write access to an object’s properties. Each instance variable of your class has an implicit getter, and a setter if needed. In dart, you can take this even further by implementing your own getters and setters. If you've had any experience in Object-Oriented Programming you'll feel right at home. Here is a basic syntax for a class: 324 | 325 | ### Example 326 | 327 | ```dart 328 | class className { 329 | fields; 330 | getters/setters 331 | constructor 332 | methods/functions 333 | } 334 | ``` 335 | 336 | ```dart 337 | class Person { 338 | String firstName; 339 | String lastName; 340 | double height; 341 | int personAge; 342 | int yearofBirth; 343 | double weight; 344 | 345 | int get age { 346 | return personAge; 347 | } 348 | 349 | void set age(int currentYear) { 350 | personAge = currentYear - yearofBirth; 351 | } 352 | 353 | // We can also eliminate the setter and just use a getter. 354 | //int get age { 355 | // return DateTime.now().year - yearofBirth; 356 | //} 357 | 358 | Person({this.firstName,this.lastName,this.personAge,this.yearofBirth,this.weight}); 359 | } 360 | ``` 361 | 362 | We can implement Person class this way: 363 | 364 | ```dart 365 | void main() { 366 | Person person = Person(firstName:"Thanos",lastName:"Rednos",yearofBirth:1990,weight:200.5); 367 | print(person.firstName); // output - Thanos 368 | print(person.lastName); // output - Rednos 369 | person.age = 2019; 370 | print(person.age); // output - 29 371 | 372 | } 373 | ``` 374 | 375 | 376 | ## Futures: Async and Await 377 | 378 | The async and await keywords provide a declarative way to define asynchronous functions and use their results. Remember these two basic guidelines when using async and await: 379 | 380 | - To define an async function, add async before the function body: 381 | - The await keyword works only in async functions. 382 | 383 | ### Example 384 | 385 | ```dart 386 | Future login() { 387 | // Imagine that this function is 388 | // more complex and slow. 389 | String userName="Temidjoy"; 390 | return 391 | Future.delayed( 392 | Duration(seconds: 4), () => userName); 393 | } 394 | 395 | // Asynchronous 396 | main() async { 397 | print('Authenticating please wait...'); 398 | print(await userName()); 399 | } 400 | 401 | ``` 402 | 403 | ## JSON and serialization 404 | 405 | Most mobile and web apps use JSON for tasks such as exchanging data with a web server. With Dart support for JSON serialization and deserialization: converting Dart objects to and from JSON, data exchange is made easy in flutter development. 406 | 407 | The following libraries and packages are useful across Dart platform: 408 | 409 | - [dart:convert](https://dart.dev/guides/libraries/library-tour#dartconvert---decoding-and-encoding-json-utf-8-and-more) 410 | Converters for both JSON and UTF-8 (the character encoding that JSON requires). 411 | - [package:json_serializable](https://pub.dev/packages/json_serializable) 412 | An easy-to-use code generation package. When you add some metadata annotations and use the builder provided by this package, the Dart build system generates serialization and deserialization code for you. 413 | - [package:built_value](https://pub.dev/packages/built_value) 414 | A powerful, opinionated alternative to json_serializable. 415 | 416 | 417 | You need to serialize and deserialize JSON in your Flutter project? [see this example](https://flutter.dev/docs/development/data-and-backend/json) to quickly get started. 418 | 419 | 420 | 421 | ## Reading and decoding a file 422 | 423 | The code snippet below reads a file and runs two transforms over the stream. It first converts the data from UTF8 and then runs it through a LineSplitter. All lines are printed, except any that begin with a hashtag, #. 424 | 425 | ### Example 426 | 427 | ```dart 428 | import 'dart:convert'; 429 | import 'dart:io'; 430 | 431 | Future main(List args) async { 432 | var file = File(args[0]); 433 | var lines = utf8.decoder 434 | .bind(file.openRead()) 435 | .transform(LineSplitter()); 436 | await for (var line in lines) { 437 | if (!line.startsWith('#')) print(line); 438 | } 439 | } 440 | 441 | ``` 442 | 443 | ## Sound null safety 444 | Sound null safety is now supported by the Dart language! 445 | 446 | When you choose to use null safety, types in your code are by default non-nullable, which means variables cannot contain null unless you explicitly allow it. Your runtime null-dereference mistakes become edit-time analysis errors with null safety. 447 | 448 | The variables in the following code are all non-nullable thanks to null safety: 449 | 450 | 451 | ```dart 452 | // None of these can ever be null in null-safe Dart. 453 | var x = 81; // Inferred to be an int. 454 | String address = getAddress(); 455 | final c = Car(); 456 | 457 | ``` 458 | 459 | Simply add ? to a variable's type declaration to indicate that it might be null: 460 | 461 | ```dart 462 | // This is now a nullable Int. 463 | int? x = null; 464 | 465 | ``` 466 | 467 | ### Enabling null safety 468 | 469 | Sound null safety is available in Dart 2.12 and Flutter 2. 470 | 471 | ### Migrating an existing package or app 472 | For instructions on how to migrate your code to null safety, see the [migration guide](https://dart.dev/null-safety/migration-guide). 473 | --------------------------------------------------------------------------------