Flutter – Global constants for the complete project


Flutter is Google’s new open-source toolkit for helping developers build iOS and Android apps with just one codebase. It uses Dart language as a common source code for both platforms. Initially, I struggled to understand the convention since every view will be considered as a Widget. Each widget will have its own state.

I came across many questions about structuring the code in DART like generic code to reuse the util methods, common styles (button, text field etc..). Here is the example for Global constants file in the flutter,

Step 1: Create a constants file under lib folder. Same as shown in the below screenshot.

Step 2: Import flutter painting library, if you want to define global padding, margins in the constants file as well

import 'package:flutter/painting.dart';

Step 3: Define the constants with const keyword,

For Strings  

const String BTN_ADD_TEXT = "Add";
const String BTN_CANCEL_TEXT = "Cancel";

For Margins, 

/// The horizontal padding included by [Tab]s.
const EdgeInsets kTabLabelPadding = EdgeInsets.symmetric(horizontal: 12.0);

/// The padding added around material list items.
const EdgeInsets kMaterialListPadding = EdgeInsets.symmetric(vertical: 8.0);

Step 4: Import the constants file in your dart file.

import 'utils/constants.dart';

Step 5: Usage of constant

child: new Center(
                 child: RaisedButton(
                  padding: const EdgeInsets.all(12.0),
                  textColor: Colors.white,
                  color: Colors.green,
                  child: new Text(BTN_ADD_TEXT), // Here BTN_ADD_TEXT is the constnt file which is defined in constants.dart file. 
                  onPressed: () {
                    // Validate will return true if the form is valid, or false if
                    // the form is invalid.
                    if (_formKey.currentState.validate()) {
                      // If the form is valid, we want to show a Snackbar
                          SnackBar(content: Text('Processing Data')));

That`s it. Now, It’s your time to make your code modular and clean.

Thanks for reading and hope you enjoy Flutter as much as I do. Feel free to leave a comment below if you have any issues, suggestions, etc.




Mobile application developer with 9+ years of experience in both Native and Hybrid Mobile applications.

%d bloggers like this: