How to Use Hexadecimal Color With Opacity in Flutter App

In this example, we are going to show you the easiest way to use Hexadecimal colors along with opacity in Flutter apps. By default, Flutter has no provision of using plain hex color code. See the example below to see how to use Hexadecimal colors in Flutter.

Color(0xFFDDDDDD)

This is the basic way to use HexaDecimal color in flutter where FF is opacity which ranges from 00-FF and DDDDDD is the Hexadecimal color code. But, This method is not suitable where you need to add 0xFF everywhere. use the following function by declaring in global file and use the function instead. 

Color HexaColor(String strcolor, {int opacity = 15}){ //opacity is optional value
    strcolor = strcolor.replaceAll("#", ""); //replace "#" with empty value
    String stropacity = opacity.toRadixString(16); //convert integer opacity to Hex String
    return Color(int.parse("$stropacity$stropacity" + strcolor, radix: 16));
    //here color format is 0xFFDDDDDD, where FF is opacity, and DDDDDD is Hex Color
}

You can use HexaColor(colorstring, opacity) function wherever you need. 

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp()); 
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Test App",
        home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget{
  
  Color HexaColor(String strcolor, {int opacity = 15}){ //opacity is optional value
     strcolor = strcolor.replaceAll("#", ""); //replace "#" with empty value
     String stropacity = opacity.toRadixString(16); //convert integer opacity to Hex String
     return Color(int.parse("$stropacity$stropacity" + strcolor, radix: 16));
     //here color format is 0xFFDDDDDD, where FF is opacity, and DDDDDD is Hex Color
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold( 
      appBar: AppBar( 
         title: Text("Use HEX Color"),
         backgroundColor: HexaColor("#EF6C00"), //where opacity is optional 
      ),
      body: Container( 
         padding: EdgeInsets.all(20),
         child: Container( 
            height:200, 
            width:double.infinity,
            color: HexaColor("#689F38", opacity: 14), //opacity ranges from 0-15
            child: Center( 
              child: Text("HEX COLOR", style: TextStyle( 
                  color: HexaColor("#FFF3E0"),
                  fontSize: 30,
              ),),
            ),
         )
      )
    );
  }
}

In this way, you can use Hexadecimal color along with opacity in Flutter apps. 

No any Comments on this Article


Please Wait...