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 @ 2020-06-08 18:41  猫叔Vincent  阅读(6558)  评论(2编辑  收藏  举报