前言

DecoratedBox可以在其子组件绘制前后绘制一些装饰,例如背景,边框,渐变等。

接口描述

const DecoratedBox({
    Key key,
    // 代表要绘制的装饰
    @required this.decoration,
    // 决定在哪里绘制Decoration。它接收DecorationPosition的枚举类型,该枚举类有两个值:background:在子组件之后绘制,即背景装饰;foreground:在子组件之上绘制,即前景。
    this.position = DecorationPosition.background,
    Widget child,
  }) : assert(decoration != null),
       assert(position != null),
       super(key: key, child: child);

oxDecoration({
  Color color, //颜色
  DecorationImage image,//图片
  BoxBorder border, //边框
  BorderRadiusGeometry borderRadius, //圆角
  List<BoxShadow> boxShadow, //阴影,可以指定多个
  Gradient gradient, //渐变
  BlendMode backgroundBlendMode, //背景混合模式
  BoxShape shape = BoxShape.rectangle, //形状
})

代码示例

// 装饰容器(DecoratedBox)
// DecoratedBox可以在其子组件绘制前后绘制一些装饰,例如背景,边框,渐变等。


import 'package:flutter/material.dart';

class DecoratedBoxTest extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('带阴影的背景色渐变按钮'),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            // 装饰容器
            DecoratedBox(
              // 绘制修饰
              decoration: BoxDecoration(
                // 背景渐变
                gradient: LinearGradient(colors: [Colors.red, Colors.orange[700]]),
                // 3像素圆角
                borderRadius: BorderRadius.circular(3.0),
                // 阴影
                boxShadow: [
                  BoxShadow(
                    color: Colors.black54,
                    offset: Offset(2.0, 2.0),
                    blurRadius: 4.0,
                  )
                ]
              ),

              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 80.0, vertical: 18.0),
                child: Text('Login', style: TextStyle(color: Colors.white),),
              ),

            ),
          ],
        ),
      ),
    );
  }
}

总结

虽然我们实现了一个渐变按钮的外观,但是它不是一个标准的按钮,即不能响应点击事件。例子中使用了LinearGradient类,它用于定义线性渐变的类。Flutter中还提供了其他渐变配置类,例如如RadialGradient、SweepGradient等。

12-24 12:18