Search code snippets, questions, articles...

dart code snippets

Isolates
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
  final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}

Future<List<Photo>> fetchPhotos(http.Client client) async {
  final response = await client
      .get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));

  // Use the compute function to run parsePhotos in a separate isolate.
  return compute(parsePhotos, response.body);
}
h
class EventResponse {
  bool? status;
  List<EventDetails>? data;
  String? message;

  EventResponse({this.status, this.data, this.message});

  EventResponse.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    if (json['data'] != null) {
      data = <EventDetails>[];
      json['data'].forEach((v) {
        data!.add(EventDetails.fromJson(v));
      });
    }
    message = json['message'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['status'] = this.status;
    if (this.data != null) {
      data['data'] = this.data!.map((v) => v.toJson()).toList();
    }
    data['message'] = this.message;
    return data;
  }
}

class EventDetails {
  String? id;
  String? organizerId;
  String? gameId;
  String? gameType;
  String? perspective;
  String? title;
  String? rules;
  String? map;
  String? badge;
  String? allowedParticipants;
  String? entryFees;
  String? noOfWinner;
  String? pointsPerKill;
  String? startDate;
  String? registrationStartDate;
  List<SlotTiming>? slotTiming;
  String? prizepool;
  String? tableImg;
  List<PriceCriteria>? priceCriteria;
  dynamic winnerDate;
  String? status;
  String? createdAt;
  String? organizerName;
  String? gameName;
  String? bannerImg;
  String? joinedPlayers;
  String? remainingPlayer;
  String? remainingInPercent;

  // Only for My Events.
  String? joinedSquad;
  String? remainingSquad;
  String? occupiedDays;
  List<Stats>? stats;

  // Only for Joined Events.
  String? slotStartTime;
  String? slotEndTime;
  String? roomId;
  String? password;

  // Common in Joined & My Events.
  List<Players>? players;

  EventDetails({
    this.id,
    this.organizerId,
    this.gameId,
    this.gameType,
    this.perspective,
    this.title,
    this.rules,
    this.map,
    this.badge,
    this.allowedParticipants,
    this.entryFees,
    this.noOfWinner,
    this.pointsPerKill,
    this.startDate,
    this.registrationStartDate,
    this.slotTiming,
    this.prizepool,
    this.tableImg,
    this.priceCriteria,
    this.winnerDate,
    this.status,
    this.createdAt,
    this.slotStartTime,
    this.slotEndTime,
    this.roomId,
    this.password,
    this.organizerName,
    this.gameName,
    this.bannerImg,
    this.joinedPlayers,
    this.remainingPlayer,
    this.remainingInPercent,
    this.players,
    this.joinedSquad,
    this.remainingSquad,
    this.occupiedDays,
    this.stats,
  });

  EventDetails.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    organizerId = json['organizer_id'];
    gameId = json['game_id'];
    gameType = json['game_type'];
    perspective = json['perspective'];
    title = json['title'];
    rules = json['rules'];
    map = json['map'];
    badge = json['badge'];
    allowedParticipants = json['allowed_participants'];
    entryFees = json['entry_fees'];
    noOfWinner = json['no_of_winner'];
    pointsPerKill = json['points_per_kill'];
    startDate = json['start_date'];
    registrationStartDate = json['registration_start_date'];
    if (json['slot_timing'] != null) {
      slotTiming = <SlotTiming>[];
      json['slot_timing'].forEach((v) {
        slotTiming!.add(SlotTiming.fromJson(v));
      });
    }
    prizepool = json['prizepool'];
    tableImg = json['table_img'];
    if (json['price_criteria'] != null) {
      priceCriteria = <PriceCriteria>[];
      json['price_criteria'].forEach((v) {
        priceCriteria!.add(PriceCriteria.fromJson(v));
      });
    }
    winnerDate = json['winner_date'];
    status = json['status'];
    createdAt = json['created_at'];
    slotStartTime = json['slot_start_time'];
    slotEndTime = json['slot_end_time'];
    roomId = json['room_id'];
    password = json['password'];
    organizerName = json['organizer_name'];
    gameName = json['game_name'];
    bannerImg = json['banner_img'];
    joinedPlayers = json['joined_players'];
    remainingPlayer = json['remaining_player'];
    remainingInPercent = json['remaining_in_percent'];
    if (json['players'] != null) {
      players = <Players>[];
      json['players'].forEach((v) {
        players!.add(Players.fromJson(v));
      });
    }
    joinedSquad = json['joined_squad'];
    remainingSquad = json['remaining_squad'];
    occupiedDays = json['occupied_days'];
    if (json['stats'] != null) {
      stats = <Stats>[];
      json['stats'].forEach((v) {
        stats!.add(Stats.fromJson(v));
      });
    }
   
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['id'] = this.id;
    data['organizer_id'] = this.organizerId;
    data['game_id'] = this.gameId;
    data['game_type'] = this.gameType;
    data['perspective'] = this.perspective;
    data['title'] = this.title;
    data['rules'] = this.rules;
    data['map'] = this.map;
    data['badge'] = this.badge;
    data['allowed_participants'] = this.allowedParticipants;
    data['entry_fees'] = this.entryFees;
    data['no_of_winner'] = this.noOfWinner;
    data['points_per_kill'] = this.pointsPerKill;
    data['start_date'] = this.startDate;
    data['registration_start_date'] = this.registrationStartDate;
    if (this.slotTiming != null) {
      data['slot_timing'] = this.slotTiming!.map((v) => v.toJson()).toList();
    }
    data['prizepool'] = this.prizepool;
    data['table_img'] = this.tableImg;
    if (this.priceCriteria != null) {
      data['price_criteria'] =
          this.priceCriteria!.map((v) => v.toJson()).toList();
    }
    data['winner_date'] = this.winnerDate;
    data['status'] = this.status;
    data['created_at'] = this.createdAt;
    data['slot_start_time'] = this.slotStartTime;
    data['slot_end_time'] = this.slotEndTime;
    data['room_id'] = this.roomId;
    data['password'] = this.password;
    data['organizer_name'] = this.organizerName;
    data['game_name'] = this.gameName;
    data['banner_img'] = this.bannerImg;
    data['joined_players'] = this.joinedPlayers;
    data['remaining_player'] = this.remainingPlayer;
    data['remaining_in_percent'] = this.remainingInPercent;
    if (this.players != null) {
      data['players'] = this.players!.map((v) => v.toJson()).toList();
    }
    data['joined_squad'] = this.joinedSquad;
    data['remaining_squad'] = this.remainingSquad;
    data['occupied_days'] = this.occupiedDays;
    if (this.stats != null) {
      data['stats'] = this.stats!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class SlotTiming {
  String? id;
  String? slotStartTime;
  String? slotEndTime;

  SlotTiming({this.id, this.slotStartTime, this.slotEndTime});

  SlotTiming.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    slotStartTime = json['slot_start_time'];
    slotEndTime = json['slot_end_time'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['slot_start_time'] = this.slotStartTime;
    data['slot_end_time'] = this.slotEndTime;
    return data;
  }
}

class PriceCriteria {
  String? rank;
  String? to;
  String? amount;

  PriceCriteria({this.rank, this.to, this.amount});

  PriceCriteria.fromJson(Map<String, dynamic> json) {
    rank = json['rank'];
    to = json['to'];
    amount = json['amount'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['rank'] = this.rank;
    data['to'] = this.to;
    data['amount'] = this.amount;
    return data;
  }
}

class Players {
  String? name;
  String? mobile;
  String? id;
  String? rank;
  String? kills;
  String? points;

  Players(
      {this.name, this.mobile, this.id, this.rank, this.kills, this.points});

  Players.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    mobile = json['mobile'];
    id = json['id'];
    rank = json['rank'];
    kills = json['kills'];
    points = json['points'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['name'] = this.name;
    data['mobile'] = this.mobile;
    data['id'] = this.id;
    data['rank'] = this.rank;
    data['kills'] = this.kills;
    data['points'] = this.points;
    return data;
  }
}

class Stats {
  String? totalPaid;
  String? entryFee;
  String? prizepool;
  String? remainingAmount;
  String? totalEarning;

  Stats(
      {this.totalPaid,
      this.entryFee,
      this.prizepool,
      this.remainingAmount, 
      this.totalEarning});

  Stats.fromJson(Map<String, dynamic> json) {
    totalPaid = json['total_paid'];
    entryFee = json['entry_fee'];
    prizepool = json['prizepool'];
    remainingAmount = json['remaining_amount'];
    totalEarning = json['total_earning'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['total_paid'] = this.totalPaid;
    data['entry_fee'] = this.entryFee;
    data['prizepool'] = this.prizepool;
    data['remaining_amount'] = this.remainingAmount;
    data['total_earning'] = this.totalEarning;
    return data;
  }
}
How to get current date in Flutter [Dart]
DateTime result = DateTime.now();

print(result);
Stop a Loop condition based in Dart
List numbers = [10, 20, 30, 40, 50];

for(final item in numbers) {
    if (item >= 30){
        break;
    }

    print("${item}");
}
Foreach Loop in Flutter [Dart]
List subjects = [
    {"id": 1, "name": "Math"},
    {"id": 2, "name": "Physics"},
    {"id": 3, "name": "Chemistry"}
];

subjects.forEach((subject) {
    // ... Do something here with items here
    print(subject["name"]);
});
Loop through a List in Flutter [Dart]
List names = ["James", "Carl", "Rick", "Tony", "Justin"];

for(var name in names) {
  print(name);
}
Delete item from a List in Flutter [Dart]
List<String> names = ["John", "Travis", "Rohit", "Mack"];

// Remove item at specific postion
names.removeAt(2);

print(names);

// -> [John, Travis, Mack]
Remove empty lists from a list of lists and flatten it using Dart
void main() {
  List listOfLists = [['a', 'b', 'c'], [], ['d', 'e'], [], [], ['f', 'g', 'h'], [], []];

  List result = listOfLists.expand((x) => x).toList();
  
  print(result);
}
Check if a String is empty or null in Dart / Flutter
void checkString(String str) {
  if (str.isEmpty) {
    print('String is empty');
  } else {
    print('String is not empty');
  }
}

void main() {
  checkString('');
  // -> String is empty
  
  checkString('hello');
  // -> String is not empty
}
Remove empty and falsey values from a List in Dart/Flutter
void main() {
  // define a Dart list
  final myList = [10, '', '', null, 20, 0, 40, 50, false];
  
  // remove falsy values from the list
  myList.removeWhere((item) => ["", null, false, 0].contains(item));
  
  // print the list
  print(myList);
}
Dart program to capitalize the first letter of a string
void main() async {
  String myStr = "devsheet";
  
  String result = "${myStr[0].toUpperCase()}${myStr.substring(1).toLowerCase()}";
  
  print(result);
}
Sort a list in ascending and descending order Dart or Flutter
List numbers = [10, 30, 50, 40, 20];

// Sort in Ascending order
numbers.sort();
print(numbers);
// -> [10, 20, 30, 40, 50]

// Sort in Descending order
numbers.sort((b, a) => a.compareTo(b));
print(numbers);
// -> [50, 40, 30, 20, 10]
Reverse a list in Flutter or Dart
List myList = ['John', 'herry', 'Carl', 'Morgan'];

myList = myList.reversed.toList();

print(myList);
Check if list is empty in Flutter/Dart
List myList = [];
  
if(myList.isEmpty) {
    print('The list is empty');
}
Dart program to remove duplicate items from a list
List numbers = [10, 30, 40, 10, 30, 20, 10, 40];
  
List result = Set.of(numbers).toList();

print(result);
Assigning a value if it's null
void main() {
  int? a; // a is null here
  a ??= 10; // will assign 10 to a as its null
  print(a); // -> Prints 10.

  a ??= 50; // will not assign 50
  print(a); // <-- Still Prints 10.

  var name = null ?? 'Ankit'; //Will assign Ankit as first value is null
  print(name);
}
Switch with connected cases
switch (this) {
    case WeatherState.clear:
        return WeatherCondition.clear;
    case WeatherState.snow:
    case WeatherState.sleet:
    case WeatherState.hail:
        return WeatherCondition.snowy;
    case WeatherState.thunderstorm:
    case WeatherState.heavyRain:
    case WeatherState.lightRain:
    case WeatherState.showers:
        return WeatherCondition.rainy;
    case WeatherState.heavyCloud:
    case WeatherState.lightCloud:
        return WeatherCondition.cloudy;
    default:
        return WeatherCondition.unknown;
}
Add item at first position of list dart
List<String> subjects = ["math", "physics", "chemistry"];
subjects.insert(0, "english");
print(subjects);
Get the length of list in Dart
List fruits = ["Apple", "Orange", "Grapes"];
int len = fruits.length;
print(len);
//-> 3
Convert string to integer Dart Program
void main() {
  String numStr = "10";
  
  int num = int.parse(numStr);
  print(num + 10);
}
Dart Program to convert a number to string
int number = 10;
print(number.toString());

int secondNum = 50;
print(secondNum.toString());
For loop in Dart
void main() {
  //Simple for loop
  for (var i = 0; i <= 2; i++) {
    print(i);
  }
  
  //Loop through dictionary of maps
  List subjects = [
    {"id": 1, "name": "Math"},
    {"id": 2, "name": "Physics"},
    {"id": 1, "name": "Chemistry"}
  ];
  for (var sub in subjects) {
    print(sub);
  }
  
  //Loop through sets
  Set names = {"Ankit", "John", "Rick"};
  for (var name in names) {
    print(name);
  }
}
Dart Program to remove multiple items from a List at once
void main() {
    List<int> numberList = [10, 20, 30, 40, 50];

    numberList.removeRange(0, 3);
    print(numberList); // -> prints [40, 50]
}
Remove List item or element using its index in Dart
void main() {
  List<int> numberList = [10, 20, 30, 40, 50];
  
  numberList.removeAt(2); //Remove value from 3rd position
  print(numberList);
}
Dart Program to remove the last element from a List
void main() {
  List<int> numberList = [1, 2, 3, 4, 5];
  
  numberList.removeLast();
  print(numberList);
}
Dart program for condition based item removal from a list
void main() {
  List<Map<String, dynamic>> names = [
    { "id": 1, "name": "John" },
    { "id": 2, "name": "Rick" },
    { "id": 3, "name": "Daryl" },
    { "id": 4, "name": "Alex" }
  ];
  // Remove items if id is greater than or equals to 3
  names.removeWhere((item) => item['id'] >= 3);
  print(names);
}
Dart Program to update or replace List items or values
void main() {
  //First Method - update 
  List myList = [1, 2, 3];
  myList[0] = 123;
  print(myList);
  
  //Second Method - using .replaceRange() method
  var myList2 = [10, 20, 30, 40, 50];
  myList2.replaceRange(0, 3, [11, 21]);
  print(myList2);
}
Dart Program to add Single or Multiple Items to a List
void main() {
  var myList = ["One", "Two"];
  
  //Add single item
  myList.add("Three");
  print(myList);
  
  //Add multiple items
  myList.addAll(["Three", "Four", "Five"]);
  print(myList);
}
Dart Collections - Create a List or Array
void main() {
    //Direct assign values
    final listOfStrings = ['one', 'two', 'three'];
    print(listOfStrings);

    final listOfInts = [1, 2, 3];
    print(listOfInts);

    // Specify type then assign values
    var listOfStrings2 = <String>[];
    listOfStrings2 = ['item 1', 'item 2'];
    print(listOfStrings2);
  
   // create list using List keyword
   List<String> list3 = [];
   list3.add("item 1");
   print(list3);
}
Assign a value to a variable if it is null using Dart
void main() {
  int? a; // a is null here
  a ??= 10; // will assign 10 to a as its null
  print(a); // -> Prints 10.

  a ??= 50; // will not assign 50
  print(a); // <-- Still Prints 10.

  var name = null ?? 'Ankit'; //Will assign Ankit as first value is null
  print(name);
}
String interpolation and formation in Dart
void main() {
  //Concate strings using ${expression}
  var name = 'Ankit';
  print('My Name is: ${name}');
  
  //Sum using ${expression}
  var sum = sumFn(5, 10);
  print(sum);
  
  //uppercase letters using ${expression}
  var uppercaseLetters = '${"john deo".toUpperCase()}';
  print(uppercaseLetters);
}

String sumFn(int x, int y) {
  return 'Sum is: ${(x+y).toString()}';
}
Dart Program to generate unique id using uuid package
import 'package:uuid/uuid.dart';
import 'package:uuid/uuid_util.dart';

void main() {
    var uuid = Uuid();

    // Generate Time based unique id using v1() method
    var uid_v1 = uuid.v1(); // -> '7b84fb90-34b4-34w2-751e-6a34b5cc454c'

    var uid_v1_exact = uuid.v1(options: {
    'node': [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
    'clockSeq': 0x1234,
    'mSecs': DateTime.utc(2021, 03, 04).millisecondsSinceEpoch,
    'nSecs': 5678
    }); // -> '710b962e-041c-11e1-9234-0123456789ab'

    // Generate random id using v4()
    var uid_v4 = uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

    // Generate crypto-random id using v4
    var uid_v4_crypto = uuid.v4(options: {'rng': UuidUtil.cryptoRNG});
    // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'

    // Generate id using v5[namespace-name-sha1-based]
    var uid_v5 = uuid.v5(Uuid.NAMESPACE_URL, 'www.google.com');
    // -> 'c74a196f-f19d-5ea9-bffd-a2742432fc9c'

    print(uid_v1);
    print(uid_v1_exact);
    print(uid_v4);
    print(uid_v4_crypto);
    print(uid_v5);
}
Shuffle objects
shuffle(var items) {
    var random = new Random();

    // Go through all elements.
    for (var i = items.length - 1; i > 0; i--) {
      // Pick a pseudorandom number according to the list length
      var n = random.nextInt(i + 1);

      var temp = items[i];
      items[i] = items[n];
      items[n] = temp;
    }

    return items;
  }
Flutter setState
class CatalogueItem extends StatefulWidget {
  final Product item;

  CatalogueItem({Key key, @required this.item}) : super(key: key);

  @override
  _CatalogueItemState createState() => _CatalogueItemState();
}

class _CatalogueItemState extends State<CatalogueItem> {

  @override
  Widget build(BuildContext context) {
    final formatDecimal = new NumberFormat("###.0#", "en_US");
    final cart = Provider.of<Cart>(context, listen: false);
    return Padding(
      padding:
          const EdgeInsets.only(top: 5.0, left: 13.0, right: 13.0, bottom: 5.0),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: new BorderRadius.circular(15.0),
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black12.withOpacity(0.1),
              blurRadius: 3.5,
              spreadRadius: 0.4,
            ),
          ],
        ),
        child: GestureDetector(
          onTap: () {
            Navigator.of(context).push(
              MaterialPageRoute(
                builder: (ctx) => ProductDetail(widget.item),
              ),
            );
          },
          child: ListTile(
            contentPadding:
                EdgeInsets.symmetric(horizontal: 5.0, vertical: 2.0),
            leading: CachedNetworkImage(
              width: 100,
              height: 100,
              imageUrl: '${widget.item.imageUrl}',
              placeholder: (context, url) => Center(
                child: SizedBox(
                  height: 50.0,
                  width: 50.0,
                  child: CircularProgressIndicator(
                    valueColor:
                        new AlwaysStoppedAnimation<Color>(Color(0xFF00AB50)),
                    strokeWidth: 2.0,
                  ),
                ),
              ),
              errorWidget: (context, url, error) => Icon(Icons.error),
            ),
            title: Container(
              height: 100,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    /// title, origin, price
                    Expanded(
                      flex: 7,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            widget.item.title,
                            style: TextStyle(
                                fontFamily: "Gotik",
                                fontWeight: FontWeight.w400,
                                fontSize: 13.0),
                          ),
                          SizedBox(
                            height: 25.0,
                          ),
                          Text(
                            "${formatDecimal.format(widget.item.price)} c",
                            style: TextStyle(
                                fontFamily: "Gotik",
                                fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                    ),

                    /// add to favourite iconButton
                    Expanded(
                      flex: 1,
                      child: Align(
                        alignment: Alignment.topCenter,
                        child: IconButton(
                          onPressed: () {
                            widget.item.toggleFavoriteStatus();
                          },
                          icon: Icon(widget.item.isFavorite
                              ? CupertinoIcons.heart_solid
                              : CupertinoIcons.heart),
                          color: Color(0xFF00AB50),
                          iconSize: 20.0,
                        ),
                      ),
                    ),
                  ]),
            ),
            subtitle: Row(
              children: <Widget>[
                /// item counter
                Container(
                  width: 120.0,
                  decoration: BoxDecoration(
                    color: Colors.white70,
                    borderRadius: BorderRadius.circular(20.0),
                    border: Border.all(
                      color: Colors.black12.withOpacity(0.1),
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      /// Decrease of value item
                      InkWell(
                        onTap: () {
                          setState(() {
                            if (widget.item.quantity != widget.item.measureStep)
                              widget.item.quantity -= widget.item.measureStep;
                          });
                        },
                        child: Container(
                          height: 30.0,
                          width: 20.0,
                          decoration: BoxDecoration(
                            border: Border(
                              right: BorderSide(
                                color: Colors.black12.withOpacity(0.1),
                              ),
                            ),
                          ),
                          child: Center(
                            child: Text(
                              "-",
                              style: TextStyle(
                                fontFamily: "Gotik",
                                fontWeight: FontWeight.bold,
                                color: Color(0xFF00AB50),
                              ),
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 5.0),
                        child: Text(
                          "${formatDecimal.format(widget.item.quantity)} ${widget.item.measure}",
                          style: TextStyle(
                            fontFamily: "Gotik",
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),

                      /// Increasing value of item
                      InkWell(
                        onTap: () {
                          setState(() {
                            widget.item.quantity += widget.item.measureStep;
                          });
                        },
                        child: Container(
                          height: 20.0,
                          width: 20.0,
                          decoration: BoxDecoration(
                            border: Border(
                              left: BorderSide(
                                color: Colors.black12.withOpacity(0.1),
                              ),
                            ),
                          ),
                          child: Center(
                            child: Text(
                              "+",
                              style: TextStyle(
                                fontFamily: "Gotik",
                                fontWeight: FontWeight.bold,
                                color: Color(0xFF00AB50),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(width: MediaQuery.of(context).size.width * 0.10),

                /// add to cart iconButton
                Container(
                    width: 60.0,
                    height: 35.0,
                    decoration: BoxDecoration(
                      color: widget.item.addedToCart
                          ? Color(0xFFaddfad)
                          : Color(0xFF00AB50),
                      borderRadius: BorderRadius.circular(25.0),
                      border: Border.all(
                          color: widget.item.addedToCart
                              ? Color(0xFF00AB50)
                              : Colors.transparent),
                    ),
                    child: IconButton(
                      icon: Icon(Icons.shopping_basket),
                      color: widget.item.addedToCart
                          ? Color(0xFF00AB50)
                          : Colors.white,
                      iconSize: 20.0,
                      onPressed: () {
                        widget.item.addedToCart
                            ? cart.removeItem(widget.item.id)
                            : cart.addItem(
                                widget.item.id,
                                widget.item.title,
                                widget.item.price,
                                widget.item.description,
                                widget.item.measure,
                                widget.item.quantity,
                                widget.item.measureStep,
                                widget.item.imageUrl);
                        setState(() {
                          widget.item.addedToCart = !widget.item.addedToCart;
                        });
                      },
                    )),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
Evenly Spaced Row in Flutter
Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      Container(
        width: 100,
        height: 100,
        color: Colors.red,
      ),
      Container(
        width: 100,
        height: 100,
        color: Colors.green,
      ),
      Container(
        width: 100,
        height: 100,
        color: Colors.blue,
      ),
    ],
  )
Simple Data Structures in Dart
void main() {
  //print(_showDateFormat());

  Dao.I.greet();
  Dao.I.incr();
  print(Dao.I.counter);

  var oneTask = new Task("A", _genId());
  _addToMap(oneTask);
  _addToList(oneTask);
  oneTask = new Task("B", _genId());
  _addToMap(oneTask);
  _addToList(oneTask);

  for (final oneTask in taskList) {
    print(oneTask.name);
  }

//   int foundIndex = taskList.indexWhere((taskItem) {
//     taskItem.name.startsWith('B');
//   });

  print("Index found at .. ");

  print(_findInList("A").id);

//   details.forEach((k, v) {
//     print(k);
//     print(v.name);
//   });
}

// Singleton start

class Dao {
  // singleton boilerplate
  Dao._internal() {}
  static final Dao _singleton = new Dao._internal();
  static get I => _singleton;

  int counter = 0;
  // business logic
  void greet() => print("Hello from singleton");
  void incr() {
    counter++;
  }
}

// Singleton end

class Task {
  String name;
  int id;
  Task(this.name, this.id);
}

// DateTime stuff
_showDateFormat() {
  var currDt = DateTime.now();
//   var newDt = DateFormat.yMMMEd().format(currDt);
//   return newDt;
}

// List stuff -------------------------
var taskList = new List<Task>();

_addToList(Task task) {
  taskList.add(task);
}

_removeFromList(int id) {
  taskList.removeWhere((item) => item.id == id);
}

Task _findInList(String query) {
  return taskList.singleWhere((taskItem) => taskItem.name == query);
}

_loopList() {
  for (final oneTask in taskList) {
    print(oneTask.name);
  }
}

// Map stuff -------------------------
var details = new Map<int, Task>();
int _genId() {
  return new DateTime.now().millisecondsSinceEpoch;
}

_addToMap(Task task) {
  details[task.id] = task;
}
Overriding theme
theme: ThemeData(
          textTheme : Theme.of(context).textTheme.apply(
            bodyColor: Colors.black,
            displayColor: Colors.grey[600],
          )
Theme
MaterialApp(
  title: title,
  theme: ThemeData(
    // Define the default brightness and colors.
    brightness: Brightness.dark,
    primaryColor: Colors.lightBlue[800],
    accentColor: Colors.cyan[600],
    
    // Define the default font family.
    fontFamily: 'Montserrat',
    
    // Define the default TextTheme. Use this to specify the default
    // text styling for headlines, titles, bodies of text, and more.
    textTheme: TextTheme(
      headline: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
      title: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
      body1: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
    ),
  )
);
Push Route
Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => ConverterRoute(
        units: this.units,
        name:this.name,
        color:this.color,
      )),
    );