样式 Builder

样式 Builder 的入口是 .style(|style| { ... })。它用于手动编写控件样式的链式配置,适合你想直接调用控件提供的强类型样式方法,而不是把样式写成 class 字符串时使用。

use flor::macros::color;
use flor::view::builder::StyleBuilder;
use flor_lys::label::{label, LabelStyleResolverExt};

let title = label("标题")
    .style(|style| {
        style
            .font_size(20.0)
            .text_color(color!("#0f172a"))
    });

基本写法

使用 .style(...) 时通常需要两个导入:

导入作用
StyleBuilder让控件拥有 .style(...) 方法。
控件自己的 *StyleResolverExt让闭包里的 style 拥有具体链式方法。

例如 Label 的样式方法来自 LabelStyleResolverExt

use flor::macros::color;
use flor::view::builder::StyleBuilder;
use flor_lys::label::{label, LabelStyleResolverExt};

let label = label("状态")
    .style(|style| style.text_color(color!("#2563eb")));

.style(...) 的闭包必须返回修改后的 style。如果要连续设置多个值,就直接链式调用。

不是所有控件都有

.style(...) 是给控件手动暴露样式链式能力用的。是否支持 .style(...)、闭包里的 style 有哪些方法,都由具体控件决定。

比如 Label 可以有 font_size(...)text_color(...) 这类方法;Button 可以有按钮变体、颜色、圆角等方法。具体方法应看控件库中该控件的文档。

use flor::macros::color;
use flor::view::builder::StyleBuilder;
use flor_lys::button::{button, ButtonStyleResolverExt, ButtonVariant};

let save = button("保存")
    .style(|style| {
        style
            .variant(ButtonVariant::Outline)
            .color(color!("#2563eb"))
    });

如果某个控件没有实现样式 builder,调用 .style(...) 时编译器会提示该方法不可用。

状态样式

样式 builder 可以按控件状态设置样式。常用状态方法包括 normal()hover()focus()active()disabled()

use flor::macros::color;
use flor::view::builder::StyleBuilder;
use flor_lys::label::{label, LabelStyleResolverExt};

let item = label("可选项")
    .style(|style| {
        style
            .text_color(color!("#334155"))
            .hover()
            .text_color(color!("#2563eb"))
    });

这段代码表示:普通状态使用深灰色,悬停状态使用蓝色。

和 class / layout 的关系

.style(...) 是控件样式的强类型写法。它适合在你已经知道目标控件支持哪些样式方法,并希望获得编译期检查时使用。

.layout(...) 是布局的强类型写法,负责显示、尺寸、间距、Flex/Grid 等布局属性。

.class(...) 是快速开发用的字符串写法。Flor 的设计理念是:class 可以描述 layout 和 style 的任意值表达,所以能用一串 class 同时设置布局和控件样式。也正因为它是为了快速开发增加的能力,class 是可选 feature。

三者可以同时使用;同一项配置以后写入的值为准。