Chrome Extension

dart code snippets

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,
      )),
    );