Color conversion in Flutter

Color conversion in Flutter

?? Excited to share a handy code snippet for color conversion in Flutter! ??

Have you ever needed to convert color codes between hexadecimal and Flutter Color objects? ?? Look no further! Here's a concise and efficient solution:

import 'package:flutter/material.dart';

void main() {
  const Color mainColor = Color(0xffFF6801);
  String mainHex = ColorConverter().colorToHex(mainColor);
  print(mainHex);
  
  const String hex = "#FF6801";
  Color color = ColorConverter().hexToColor(hex);
  print(color);
}

class ColorConverter {
  Color hexToColor(String hexCode) {
    try {
      final int parsedColor = int.parse(hexCode.substring(1, 7), radix: 16);
      return Color(parsedColor + 0xFF000000);
    } catch (e) {
      print("Invalid hex code: $hexCode");
      return const Color(0xff000000);
    }
  }

  String colorToHex(Color color) {
    return '#${color.value.toRadixString(16)}';
  }
}
        

? What does this code do?

  • It provides two functions: hexToColor converts a hexadecimal color code to a Flutter Color object, and colorToHex converts a Color object back to its hexadecimal representation.
  • Error handling is included for invalid hexadecimal color codes.

?? Why is it useful?

  • This code simplifies the process of converting color codes, which is commonly needed in Flutter app development.
  • It's efficient and easy to integrate into your projects, saving you time and effort.

?? How can you use it?

Simply copy and paste this code into your Flutter project! You can then utilize the hexToColor and colorToHex functions wherever you need color conversion.

Happy coding! Feel free to share your thoughts or questions below. Let's empower each other in the world of Flutter development! ?? #Flutter

要查看或添加评论,请登录

Eslam Elezaby的更多文章

  • Stlesswidget lifecycle.

    Stlesswidget lifecycle.

    In Flutter, StatelessWidget is a basic building block for creating user interfaces. Unlike StatefulWidget…

  • StatefulWidget lifecycle:

    StatefulWidget lifecycle:

    1- This method is called only once during the widget's lifetime. the framework calls the method of the associated to…

  • OOP in Brief

    OOP in Brief

    Class: A blueprint or template for creating objects defines the properties and behaviors common to all objects. Object:…

  • What is SOLID ?

    What is SOLID ?

    Single Responsibility: a class should have only one responsibility or job. Open/Closed: Software entities ( classes…

  • Array and Linked?List.

    Array and Linked?List.

    Array Arrays have a fixed size meaning that you need to specify the array size when you declare it. All elements in an…

社区洞察

其他会员也浏览了