//! BAD
final yyyyMMddstring = DateFormat('yyyy/MM/dd').format(DateTime.now());
//* GOOD
final currentDate = DateFormat('yyyy/MM/dd').format(DateTime.now());
Future.wait
to make concurrent API calls//! BAD
Future callMultipleApis() async {
await getUserInfo();
await getLocations();
}
//* GOOD
Future callMultipleApis() async {
await Future.wait([
getUserInfo(),
getLocations(),
]);
}
//! BAD
Future.delayed(const Duration(minutes: 30), () {
debugPrint('some logic here');
});
//* GOOD
const MINUTES_DURATION = 30;
Future.delayed(const Duration(minutes: MINUTES_DURATION), () {
debugPrint('some logic');
});
//----OR----
const HALF_AN_HOUR = Duration(minutes: 30);
Future.delayed(HALF_AN_HOUR, () {
debugPrint('some logic');
});
const info = ['John', '31', '[email protected]'];
//! BAD
final infoPerson = Person(fullName: info[0], age: info[1], email: info[2]);
infoPerson.saveInfo();
//* GOOD
final fullName = info[0];
final age = info[1];
final email = info[2];
final infoPerson = Person(fullName: fullName, age: age, email: email)
..saveInfo();
Avoid mental mapping
const staffs = ['Holmes', 'Dane', 'Dyno', 'Maker'];
b. and we perform some actions with this list
//! BAD
for (final n in staffs) {
doSomething();
//...
//...
//...
//...
//...
//...
//"n" is defined as what?
doStuff(n);
}
//* GOOD
for (final staffName in staffs) {
doSomething();
//...
//...
//...
//...
//...
//...
doStuff(staffName);
}
Prefer default parameters over short-circuiting or conditionals
//! BAD
void logErrorWithDefaultInternal({String? errorText}) {
print(errorText ?? 'Internal Server Error');
}
//* GOOD
void logErrorWithDefaultInternal({String errorText = 'Internal Server Error'}){
print(errorText);
}
const numbers = [33, 10, 99, 275, -100, 9000, -300];
//!BAD
List getGenericNumbers() {
final result = numbers.where((number) {
if (number.isOdd && number > 0) {
return true;
}
return false;
}).toList();
return result;
}
//!GOOD
bool checkNumberIsOddAndPositive(int number) {
return number.isOdd && number > 0;
}
List getListPositiveOddNumbers() {
final result = numbers.where(checkNumberIsOddAndPositive).toList();
return result;
}
// First, we have 3 classes Person, Student, Teacher.
// Student and Teacher both extend Person
class Person {}
class Student extends Person {
//properties...
}
class Teacher extends Person {
//properties...
}
//! BAD
Widget _buildAvatarStudent() {
return Image.asset('assets/images/student.png');
}
Widget _buildAvatarTeacher() {
return Image.asset('assets/images/teacher.png');
}
//! GOOD
Widget _buildAvatar(Person person) {
String image = 'assets/images/placeholder.png';
if (person is Student) {
image = 'assets/images/student.png';
} else if (person is Teacher) {
image = 'assets/iamges/teacher.png';
}
return Image.asset(image);
}
final
for variables that won't be reassigned.const
for values that will not change during runtime.