How to Add Hexadecimal Colors in Flutter

By default, you cannot add hexadecimal color code directly to Flutter. In this blog post, let’s check how to add hex color codes in Flutter.

The hexadecimal string is not accepted because the Colors class accepts only integers. Hence, while specifying hexadecimal colors we need to convert it into integers. For this, you just need to append 0xFF in front of the color code. 0xFF is the part which specifies the opacity of the given color.

For example, if I want to use hexadecimal color code #00BCD1 then I should convert it as 0xFF00BCD1 . Still confused? Go through the following example where I change the background color of the scaffold widget.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        backgroundColor: Color(0xff00BCD1),
        appBar: AppBar(
          title: Text('Flutter hexa color example'),
        ),
        body: Center(child: Body()),
      ),
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class Body extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text('How Are You?');
  }
}

That’s it. I hope now you know how to add hex color codes in Flutter.

Leave a Comment

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