Flutter Best Practices — Part 1

By | June 28, 2023

1. Placeholder Widgets

Use SizedBox instead of Container as Placeholder widgets.

Take a look at the below use-case

return _loaded ? Container() : YourWidget();

The SizedBox is a const constructor and creates a fixed-size box. The width and height parameters can be null to indicate that the size of the box should not be constrained in the corresponding dimension.

Hence, when we are implementing a placeholder, SizedBox should be used instead of Container.

return _loaded ? SizedBox() : YourWidget();

Even better

return _loaded ? SizedBox.shrink() : YourWidget();

2. Define Theme

Define Theme of the app as well as a first priority to avoid the headache of changing the theme in future updates, Setting up Theme is surely confusing but one time task. Ask your designer to share all the Theme related data like, Colors, font sizes and weightage.

MaterialApp(
  title: appName,
  theme: ThemeData(
    // Define the default brightness and colors.
    brightness: Brightness.dark,
    
    // You can add the color from the separate 
    // class here as well to maintain it well.
    primaryColor: Colors.lightBlue[800],
    // Define the default font family.
    fontFamily: 'Georgia',
    // Define the default `TextTheme`. 
    // Use this to specify the default
    // text styling for headlines, titles, bodies of text, and more.
    textTheme: const TextTheme(
      headline1: TextStyle(
        fontSize: 72.0, 
        fontWeight: FontWeight.bold,
    ),
    headline6: TextStyle(
        fontSize: 36.0, 
        fontStyle: FontStyle.italic
    ),
    bodyText2: TextStyle(
        fontSize: 14.0, 
        fontFamily: 'Hind',
    ),
    ),
  ),
  home: const MyHomePage(
    title: appName,
  ),
);


You can do much more with the Theme, which is defining your custom TextField, Card, Bottom Navigation Bar themes for once and use it straight away in the app.

class AppTheme {
  AppTheme();

  static AppTheme? _current;

  // ignore: prefer_constructors_over_static_methods
  static AppTheme get current {
    _current ??= AppTheme();
    return _current!;
  }

  static ThemeData? lightTheme = ThemeData(
    scaffoldBackgroundColor: AppColors.screenBackground,
    primaryColor: AppColors.blue,
    colorScheme: const ColorScheme.light(secondary: Colors.white),
    cardColor: Colors.white,
    floatingActionButtonTheme: const FloatingActionButtonThemeData(
      backgroundColor: AppColors.blue,
    ),
}

3. Using ‘if’ instead of Ternary Operator

Let’s take a look at below example

Row(
children: [
Text("Hello Flutter"),
Platform.isIOS ? Text("iPhone") : SizeBox(),
]
);

Use dart’s built in ‘if’ statement in the layout.

Row(
children: [
Text("Hello Flutter"),
if (Platform.isIOS) Text("iPhone"),
]
);

Use it for array of widgets too

Row(
children: [
Text("Hello Flutter"),
if (Platform.isIOS) ...[
Text("iPhone")
Text("MacBook")
],
]
);

4. Use const widgets whenever possible

Here the TitleWidget doesn’t change on every build, so its better to make it a const widget.

Advantage: Faster build because TitleWidget will be skipped in the build since it wont change during the process.

class MyWidget extends StatelessWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisSize: MainAxisSize.min,
        children: const [
          TitleWidget(),
        ],
      ),
    );
  }
}

class TitleWidget extends StatelessWidget {
  const TitleWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Padding(
      padding: EdgeInsets.all(10),
      child: Text('Home'),
    );
  }
}

5. Naming Conventions

Classes, enums, typedefs, and extensions name should in UpperCamelCase.

class MyWidget { ... }
enum Choice { .. }
typedef Predicate<T> = bool Function(T value);
extension ItemList<T> on List<T> { ... }


Libraries, packages, directories, and source files name should be in snake_case(lowercase_with_underscores).

library firebase_dynamic_links;
import 'my_lib/my_lib.dart';

Variables, constants, parameters, and named parameters should be in lowerCamelCase.

var item;
const cost = 3.14;
final urlScheme = RegExp('^([a-z]+):');
void sum(int price) {
 // ...
}

Leave a Reply

Your email address will not be published. Required fields are marked *