Flutter - primarySwatch自定义颜色
2020-06-09 10:56
1346 查看
一般新建了一个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';//# 1ff8 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'), ); } }
相关文章推荐
- 自定义ListView的Item项在pressed或selected等状态时的颜色
- android中自定义view---实现竖直方向的文字功能,文字方向朝上,同时提供接口,判断当前touch的是哪个字符,并改变颜色
- ionic tabs完美自定义背景及点击和正常的颜色
- 自定义iOS7导航栏背景,标题和返回按钮文字颜色
- Android代码中设置图片,文本自定义颜色,Linearlayout等控件设置背景
- 利用jquery修改elment的自定义组件多选框el-select(修改多选框的颜色)
- flutter自定义Loading
- 自定义 navigation 颜色 右边按钮 iphone
- Android中自定义SeekBar的背景颜色,进度条颜色,以及滑块的图片
- 自定义iOS7导航栏背景,标题和返回按钮文字颜色
- Android之自定义EditText光标和下划线颜色
- 自定义颜色清屏
- 自定义Spinner在界面上的颜色
- Pycharm 设置自定义背景颜色的图文教程
- iOS 7+自定义导航栏背景,标题和返回按钮文字颜色
- 自定义SimpleAdapter实现修改listview的每行的颜色
- 自定义UITabBar的背景图片或者颜色
- UIColor用自定义颜色,TableView去掉背景色
- 自定义Dialog用于电话咨询,具有从底部弹出效果,点击按钮改变颜色
- 设置UITableView Section的背景颜色和字体颜色-自定义Section