Flutter - Other

Use Cascades Operator

If we want to perform a sequence of operations on the same object then we should use the Cascades(..) operator.


Do

var path = Path()
	..lineTo(0, size.height)
	..lineTo(size.width, size.height)
	..lineTo(size.width, 0)
	..close(); 


Don't

var path = Path();
	path.lineTo(0, size.height);
	path.lineTo(size.width, size.height);
	path.lineTo(size.width, 0);
	path.close(); 

Use Const in Widgets

The widget will not change when setState call we should define it as constant. It will prevent the widget to rebuild so it improves performance.


Container(
  padding: const EdgeInsets.only(top: 10),
  color: Colors.black,
  child: const Center(
    child: const Text(
      "No Data found",
      style: const TextStyle(fontSize: 30, fontWeight: FontWeight.w800),
    ),
  ),
);

Use dart:io library to write a platform-specific code

import 'dart:io' show Platform;

...

if(Platform.isIOS) {
  doSomethingforIOS();
}

if(Platform.isAndroid) {
  doSomethingforAndroid();
}

Use expression function bodies

For functions that contain just one expression, you can use an expression function. The => (arrow) notation is used for expression function.


Do

get width => right - left;
	
Widget getProgressBar() => CircularProgressIndicator(
  valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
);


Don't

get width {
  return right - left;
}
 
Widget getProgressBar() {
  return CircularProgressIndicator(
    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
  );
}

Use if condition instead of conditional expression

Many times we need to render a widget based on some conditions in Row and Column. If conditional expression return null in any case then we should use if condition only.


Do

Widget getText(BuildContext context) {
  return Row(
    children: [
      Text("Hello"), 
      if (Platform.isAndroid) Text("Android")
    ]
  );
}


Don't

Widget getText(BuildContext context) {
  return Row(
    children: [
      Text("Hello"),
      Platform.isAndroid ? Text("Android") : null,
      Platform.isAndroid ? Text("Android") : SizeBox(),
      Platform.isAndroid ? Text("Android") : Container(),
    ]
  );
}

Use interpolation to compose strings

Use interpolation to make string cleaner and shorter rather than long chains of + to build a string.


Do

var description = 'Hello, $name! You are ${year - birth} years old.';


Don't

var description = 'Hello, ' + name + '! You are ' + (year - birth).toString() + ' years old.';

Use Map Instead of Switch Statement for Lookup

Don't do this

String getCaffeine(String type) {
  switch (type) {
    case 'Coffee':
      return '95 mg';
    case 'Redbull':
      return '147 mg';
    case 'Tea':
      return '11 mg';
    case 'Soda':
      return '21 mg';
    default:
      return 'Not found';
  }
}


void main() {
  print(getCaffeine('Coffee'));   // Output: 95 mg
  print(getCaffeine('Soda'));     // Output: 21 mg
  print(getCaffeine('Juice'));    // Output: Not found
}


Do this

String getCaffeine(String type) {
  const caffeineMap = {
    'Coffee': '95 mg',
    'Redbull': '147 mg',
    'Tea': '11 mg',
    'Soda': '21 mg',
  };

  return caffeineMap[type] ?? 'Not found';
}


void main() {
  print(getCaffeine('Coffee'));   // Output: 95 mg
  print(getCaffeine('Soda'));     // Output: 21 mg
  print(getCaffeine('Juice'));    // Output: Not found
}

Use of Null safe (??) Operator

Prefer using ?? (if null) and ?. (null aware) operators instead of null checks in conditional expressions. It reduces code and make code more cleaner.


Don't

var side = rightside == null ? leftside : rightside;
var side = rightside ?? leftside;


Do

var side = rightside ?? leftside; //If Null
var userName = user?.name; //Null aware

Use only relative imports for files in lib/

When create multiple files within our lib/ folder and import it in one another. Use of absolute and relative together can create confusion, To avoid this we should use relative imports for files.


Don't

import package:appname/utilities/ server_config.dart;


Do

import'./utilities/server_config.dart;

Use raw string

A raw string can be used to avoid escaping only backslashes and dollars.


Do

var s = r'This is demo string \ and $';


Don't

var s = 'This is demo string \\ and \$';

Use relative imports for files in lib

When use relative and absolute imports together then It is possible to create confusion when the same class gets imported from two different ways. To avoid this case we should use a relative path in the lib/ folder.


Do

import '../../../utils/dialog_utils.dart';


Don't

import 'package:demo/src/utils/dialog_utils.dart';

Use spread collections

When existing items are already stored in another collection, spread collection syntax leads to simpler code.


Do

var y = [4,5,6];
var x = [1,2,...y];


Don't

var y = [4,5,6];
var x = [1,2];

x.addAll(y);