Fork me on GitHub

Flutter - primarySwatch自定义颜色

一般新建了一个Flutter项目,`primarySwatch`颜色被设置成`Colors.blue`,如果我们想要自定义一个HEX值,那么你可能会想到使用

`primarySwatch: Color.fromARGB(a, r, g, b)`.

不过这样是编译不过的。

因为`primarySwatch`是`MarerialColor`类型,而刚才返回的是Color类型。

那么我们应该寻找其他方法。

新建一个color.dart文件,我们需要把普通的比如Hex color转换成`MaterialColor`

复制代码
import 'dart:ui';
import 'package:flutter/material.dart';

//调用的时候需要把hex改一下,比如#223344 needs change to 0xFF223344
//即把#换成0xFF即可
MaterialColor createMaterialColor(Color color) { List strengths = <double>[.05]; Map swatch = <int, Color>{}; final int r = color.red, g = color.green, b = color.blue; for (int i = 1; i < 10; i++) { strengths.add(0.1 * i); } strengths.forEach((strength) { final double ds = 0.5 - strength; swatch[(strength * 1000).round()] = Color.fromRGBO( r + ((ds < 0 ? r : (255 - r)) * ds).round(), g + ((ds < 0 ? g : (255 - g)) * ds).round(), b + ((ds < 0 ? b : (255 - b)) * ds).round(), 1, ); }); return MaterialColor(color.value, swatch); }
复制代码

 

这样我们就可以愉快的使用`createMaterialColor`函数了,因为她直接返回`MaterialColor`

 

复制代码
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: createMaterialColor(Color(0xFF223344)),
        // This makes the visual density adapt to the platform that you run
        // the app on. For desktop platforms, the controls will be smaller and
        // closer together (more dense) than on mobile platforms.
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
复制代码

 

posted @   猫叔Vincent  阅读(6590)  评论(2编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
历史上的今天:
2019-06-08 Flutter - flutter desktop embedding / flutter 桌面支持
点击右上角即可分享
微信分享提示