Skip to content

Instantly share code, notes, and snippets.

@bitsnaps
Last active August 3, 2021 18:34
Show Gist options
  • Save bitsnaps/6232d04d8f95fdce0fb955ed850bbf9c to your computer and use it in GitHub Desktop.
Save bitsnaps/6232d04d8f95fdce0fb955ed850bbf9c to your computer and use it in GitHub Desktop.
A simple dart sheet summary
// Dart is a C-Like strongly static typed language
// variable are pass-reference-by-value
// Everything is an Object
/*
* Data Type in Dart
Data Type | Keyword | Description
Number | int, double, num | Numbers in Dart are used to represent numeric literals
Strings | String | Strings represent a sequence of characters
Booleans | bool | It represents Boolean values true and false
Lists | List | It is an ordered group of objects
*/
// Every declaration of an object is an instance of Null (which is an object)
// Comment just like Java except this one:
/// Code doc Comment
/// It uses markdown syntax to generate code docs when making API
// import with 'dart:libraryName'
import 'dart:collection';
import 'dart:math' as math;
//import 'dart:io'; // deal with files (dones't work in dartpad)
// Dart will execute main() method anywhere in the project
void main() {
// int, double, num: are numeric data types
double myDouble = 0; // Dart will add decimal prefix 0.0
print('myDouble: $myDouble');
// num can be either int or double
num myNum = 0.1;
myNum = 1;
print('myNum: ${myNum}');
int i = 0;
myNum = i;
//i = myNum; // ERROR
// divide and return an integer
int result = 12 ~/ 4;
print("12 / 4 = ${result}");
// Rune can be defined as an integer used to represent any Unicode code point.
print('Code units of "Hello" = ${"A".codeUnits}"');
print("A".runes);
// Symbols are mainly used for libraries and reflection
Symbol lib = new Symbol("foo_lib");
print(lib);
// RGB value can be sotred in an int
int hex = 0xEADEBAEE;
print(hex);
// Constants can't be chaned
const CONST_VALUE = 3;
print(CONST_VALUE);
// final can't be changed are usually used in classes and functions
final f = 5;
print(f);
// var is mutable, its type will be infered and won't be changed
var v = "message";
//v = false; ERROR!
print(v);
// dynamic is evaluated by static type checking, it can change value and data type
dynamic d = "dynamic text";
d = 123;
print(d);
// Null operator is supported
var hasString = (d == 123) ?? "default string";
assert( hasString == 'default string');
// conversions can be done with: toInt(), int.parse()...
print(d.toInt());
print(int.parse("5"));
// Strings have single-quote or double-quote for delimiters iwth no difference.
print("It doesn't make a difference");
print('<a href="#">Home</a>');
print('''
Multiline string can be used with triple-quote
''');
// String interpolation can be done with $ (you can escape it with \$)
print("value of f = $f, you can escape dollar symbol with: \$${f}");
// Functions can be declared in a global space, they can be nested
String f1() { return ""; }
print(f1());
String f2() => "";
print(f2());
int f3(int e){
int f4(int i) => i+i;
return f4(e);
}
print(f3(2));
// Anonymous functions don't include a name but can take number of args
void example2(){
void nested1(Function fn){
}
nested1( () => print("Example2 nested 1") );
}
example2();
// You can specify the names of the parameter to be used by the declaration of another function
void example3(){
void f5(fn(String msg)){
fn('Message');
}
f5( (s) => print(s) );
}
example3();
// Functions have closure access to outer variables
var s = "message";
void example4(){
void nested1(fn(i)){
fn(s);
}
nested1 ( (s) => print(s) );
}
example4();
// Anonymous instance can be created with or without `new` keyword
new Example5().sayHello();
// Class declaration can have a body with: methods, variables, classes
Example6().sayHello();
// Class methods and variables are declared with "static" keyword
Example7.sayHello();
// Dart support Generics
GenericExample<Object>().printType();
// Check variable type with `is` or `runtimeType`
if (s is String || s.runtimeType == String){
print(s);
}
// List on the outer scope of class have to be constant
List l = List.filled(3, 1, growable: true); l = [1,2]; // or: List l = [1,2];
l.add(3);
print(l);
// but arrays and maps are not, they can be made constant by declaring them with `const``
const a = [1,4,5];
print(a);
List<String> days = [];
days.add("Sat"); days.add("Sun"); days.add("Mon");
print(days);
Map map = {1: "Jan", 2:"Fev", 3: "Mar"};
print(map);
print(map[2]);
// Assigning a list from variable will result in creation of Iterable
var iterableList = days;
print(iterableList.runtimeType); // == JSArray<String>
assert( iterableList.runtimeType != List );
// Loops with forEarch, for, map...
days.forEach( (day) => print(day));
// for, do/while & while/do, for/in... are just like Java
for (int i = 0; i < days.length; i++){
print(days[i]);
}
for (final day in days){ print(day); }
// Iterate over a map
map.forEach( /* MapEntry */ (key, value) => print(value) );
map.keys.forEach( (key) => print(key) );
map.values.forEach( (value) => print(value) );
// You can iterate over a String
String reversed = "";
for (int i = s.length-1; i >= 0; i--){
reversed += s[i];
}
print(reversed);
// DateTime provides date/time arithmetic
var now = new DateTime.now();
print("Now it's: ${now}");
var tomorrow = now.add(new Duration(days: 1));
print("Tomorrow will be: ${tomorrow}");
// RegEx are supported
var re = new RegExp("^s.+?g\$");
void match(s){
if (re.hasMatch(s)){
print("regexp matches '${s}'");
} else {
print("regexp doesn't match '${s}'");
}
}
match("some string");
match("some");
// Boolean expression support implicit conversions and dynamic type
var s1 = null;
if (s1 != null){
print("s1 is not Null");
}
s = '';
if (s == ''){
print("s is empty");
}
var b = null;
try {
if (b){
print("true, b is $b");
} else {
print("false, b is $b");
}
} on RangeError {
print("RangeError occurs");
} catch(e){
print(e);
//throw e; // throw takes any object as parameter
}
finally { print("finally block is optional"); }
// Efficient String can be created with StringBuffer
var sb = new StringBuffer();
sb.write("Hello");
if (sb.isNotEmpty){
// Concatination can also be done with space
print("${sb} " "there!");
}
// Getter can be defined with `get` keyword
Example8().show();
Example9().show();
// Mixin ca be used to simulate multiple inheritance using `with` keyword
Example10().show();
// You can set parameters with `this.parametername` prefix and it will set the parameter on an instance variable of same name
var ex11 = Example11();
ex11.username = 'Ali';
assert(ex11.username == 'Ali');
// Parameters are optional when declared with [] and you can use named parameter when declared with {}
print( Example12("Ali", 54) );
print( Example12("Ali", 54, 10000.0) );
// You can extends (or implements) BaseIterable from 'dart:collection'
print( Example13() );
//IterableBase
// Use library (math)
assert(math.sqrt(9) == 3);
assert( 3 == 3.0 ); // true
// You can implement any class (or abstract class) interface with `implements` keyword
new Human().walk();
/* //List all files (need to import 'dart:io')
Directory dir = Directory('.');
dir.list(recursive: false).forEach((f) => print(f.path) );
*/
// You can use a class like method with call() function
var ex14 = Example14();
print( ex14());
// private method/variables are defined with underscore "_",
// they inherited to the super classes
if (Example9 is Example8){
print('Example 9 is NOT Example8');
} else {
var ex9 = Example9();
// can be called without castying (because Example9 inherits from Example8)
ex9._privateShow();
}
// Type casting can be used to cast object to Map (or from List of class to List of super class)
// This may throw a runtime exception (although it works in some cases!)
try {
Map m2 = Example15() as Map;
print(m2);
} on TypeError {
print('Runtime TypeError*********');
} catch(ex){
print('Error: $ex');
}
List<Example8> listExample9 = <Example9>[] as List<Example8>;
assert(listExample9.isNotEmpty);
// You can use <dynamic> List to collect multiple object from different type
List<dynamic> listExamples = <dynamic>[Example9(),Example8()];
assert(listExamples.length == 2);
print('done.');
} // end of main()
/*******************************************************************
******************************* Example of Classes *****************
********************************************************************/
// Class declaration has closure access
void f6() => { print("Hello5") };
class Example5 {
void sayHello(){
f6();
}
}
class Example6 {
var message = "Hello6";
void say(s) => { print(s) };
void sayHello(){
say(this.message);
}
}
class Example7 {
static var classVariable = "Hello7";
static void sayHello(){
print(classVariable);
}
}
class GenericExample<T> {
void printType(){
print("Instantiated with type: $T");
}
}
class Example8 {
int _secret = 123;
List<String> _names = [];
List<String> get names => _names;
set names(List<String> list){
this._names = list;
}
int get length => _names.length;
void add(String name){
_names.add(name);
}
// Constructor
Example8(){
_names = ["a","b"];
}
@override
String toString(){
return "${this._names.toString()} with length: ${this._names.length}";
}
void show(){
if (this._names.isEmpty){
print("List is Empty!");
return;
}
print("Class of type: ${runtimeType} = ${this.toString()}" );
}
// method & variable are private if they start with "_" symbol
void _privateShow(){
if (this._names.isEmpty){
print("List is Empty!");
return;
}
print("[PRIVATE] type: ${runtimeType} = ${this.toString()}, serect N°:$_secret..." );
}
}
class Example9 extends Example8 {
int maxLength = 10;
Example9(): super(){
if (this.length > 10){
//throw new Exception("Error max length can exceed 10.");
throw("Error max length can exceed 10.");
}
}
@override
String toString(){
return super.toString() + " with max length = ${this.maxLength}";
}
}
class Utils {
void removeAll(List<String> list){
list.clear();
}
}
class Example10 extends Example9 with Utils {
Example10(): super(){
removeAll(this._names);
}
// You can only have one unnamed constructor,
Example10.nonEmptyList({minLength: 5}) : super();
}
class Example11 {
var username = null;
Example11({this.username});
}
class Example12 {
String name = "";
int age = 0;
double salary = 0.0;
Example12(name, age, [salary]);
Example12.create({name, age, salary});
@override
String toString(){
return "Name: $name, Age: $age";
}
}
// IterableBase from 'dart:collection'
class Example13 extends IterableBase {
var names = [];
Example13(){
this.names = ["one", "two", "three"];
}
@override
Iterator get iterator => names.iterator;
String toString(){
return names.toString();
}
}
abstract class Walkable {
void walk();
}
class Human implements Walkable {
void walk(){
print("I can walk!");
}
}
class Example14 {
String call(){
return "Created Example14 with call()";
}
}
class Example15 {
late String username;
late int age;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment