Lyscms+
登录注册
Flutter1.22 - ThemeData.primarySwatch自定义主题颜色
原创Flutter1.22 - ThemeData.primarySwatch自定义主题颜色

Flutter
image
Flutter_Toker
2020-12-12 21:37:49
阅读数:144
ThemeDataprimarySwatch

问题背景

    当我们使用开发工具创建一个flutter项目后,生成的模版项目结构中默认有个计数的demo,但是这个默认的demo里面的主题颜色设定为Colors.blue

截屏2020-12-12 21.21.40.png

但是我们想更改一个我们自己想要的颜色,这时我想到更换一个颜色那就看这个Colors类有没有我们想要的颜色,发现一些可以,一些会编译不过,编译不过的,我们看到源码类型不匹配,如果没有自己想要的颜色,我们可能想到Color有没有构造方法,自定义一个HEX值,那么你可能会想到使用primarySwatch: Color.fromARGB(a, r, g, b),不过这样是编译不过的,发现primarySwatch属性的类型是MaterialColor

探索

于是我们想到MaterialColor的构造方法,经过查看源码:

ThemeData. primarySwatch:

factory ThemeData({
    Brightness? brightness,
    VisualDensity? visualDensity,
    MaterialColor? primarySwatch,
    Color? primaryColor,
    Brightness? primaryColorBrightness,
    Color? primaryColorLight,
    Color? primaryColorDark,
    ...

MaterialColor存在构造方法

/// The `primary` argument should be the 32 bit ARGB value of one of the
/// values in the swatch, as would be passed to the [new Color] constructor
/// for that same color, and as is exposed by [value]. (This is distinct from
/// the specific index of the color in the swatch.)
const MaterialColor(int primary, Map<int, Color> swatch) : super(primary, swatch);

有了构造方法那就好办了,我们就可以用构造方法构造出来一个自己想要的主题颜色对象了,哈哈,对就是这样

构造MaterialColor对象

新建一个ColorUtils.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

import 'package:flutter/material.dart';
import 'tools/ColorUtils.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'FlutterPlus Template',
      theme: ThemeData(
        primarySwatch: createMaterialColor(Color(0xFF6f42c1)),
        // primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

更改之后的主题颜色:

截屏2020-12-12 21.35.41.png

一个人在年轻的时候浪费自己的才华与天赋是一件非常可惜的事情,文章最后更新于:2020-12-12 21:37:49

Java内存模型(JMM)
什么是Java注解?
loading