Coding style
Last modified on Tue 09 Nov 2021

Style guidelines

Good:

Widget build(BuildContext context) {
  return MaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(primarySwatch: Colors.blue),
  );
}

Bad:

Widget build(BuildContext context) {
  return MaterialApp(title: 'Flutter Demo', theme: ThemeData(primarySwatch: Colors.blue));
}

Constants

// Definiton
class Fonts {
  Fonts._();
  static const String spaceGrotesk = 'SpaceGrotesk';
}

// Usage
Fonts.spaceGrotesk
const double newtonUnit = 9.8;

double massInNewton(double massInKg) {
  return massInKg * newtonUnit;
}

Function notations

Good:

void print(List<int> numbers) {
  numbers.forEach((element) => printSqrt(element.toDouble()));
}

void printSqrt(double number) {
  double sqrtValue = sqrt(number);
  print(sqrtValue);
}

Bad:

void print(List<int> numbers) {
  numbers.forEach((element) {
    double value = element.toDouble();
    double sqrtValue = sqrt(number);
    print(sqrtValue);
  });
}

Good:

strings.forEach(print);

Bad:

strings.forEach((element) => print(element));

Avoid large functions and widgets

Good:

class _MyScaffold extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Material(child: Text('Hello, world!'));
  }
}

void main() {
  runApp(MaterialApp(
    title: 'My app',
    home: _MyScaffold(),
  ));
}

Bad:

Widget _myScaffold() {
  return Material(child: Text('Hello, world!'));
}

void main() {
  runApp(MaterialApp(
    title: 'My app',
    home: _myScaffold(),
  ));
}

Return and break early

Good:

if (!n.isNumber) {
  return;
}
// Use n here

Bad:

if (n.isNumber) {
  // Use n here
} else {
  return;
}

Comments

  /// Throws a [StateError] if ...
  /// similar to [anotherMethod()], but ...

Imports

Good:

  import 'constants.dart';

Bad:

  import 'package:flutter_myApp/constants.dart';