Как создать RaisedButton с закругленным углом и градиентным фоном? - PullRequest
1 голос
/ 17 марта 2019

Я пытался создать рельефную кнопку с закругленным углом и градиентным фоном, но безуспешно. Я могу реализовать только одно или другое. Прошло 2 часа, и я сам не нашел решения о том, как совместить закругленный угол и градиентный фон.

Ниже приведены мои коды моей последней попытки реализовать выпуклую кнопку с закругленным углом и градиентным фоном.

Пользовательский класс GradientButton

class RaisedGradientButton extends StatelessWidget {
  final Widget child;
  final Gradient gradient;
  final double width;
  final double height;
  final Function onPressed;

  const RaisedGradientButton({
    Key key,
    @required this.child,
    this.gradient,
    this.width = double.infinity,
    this.height = 50.0,
    this.onPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      height: 50.0,
      decoration: BoxDecoration(
        gradient: new LinearGradient(
          colors: [
            Colors.blue,
            Colors.red,
          ],
          begin: FractionalOffset.centerLeft,
          end: FractionalOffset.centerRight,
        ),
      ),
      child: Material(
        shape: new RoundedRectangleBorder(
            borderRadius: new BorderRadius.circular(128.0)),
//        color: Colors.transparent,
        child: InkWell(
            onTap: onPressed,
            child: Center(
              child: child,
            )),
      ),
    );
  }
}

Как я использую приведенный выше код:

RaisedGradientButton(
    onPressed: navigateToNextPage,
        child: Text("Select Community"),
)

Как это выглядит:

enter image description here

Как вы можете видеть, градиент есть, но когда я пытаюсь создать закругленный угол, он перекрывается, а градиент позади.

Ответы [ 2 ]

2 голосов
/ 17 марта 2019

Я предлагаю вам поставить Container с градиентом ниже кнопки на Stack и обрезать его углы с помощью ClipRRect, оставляя цвет кнопки прозрачным.Таким образом вы сохраняете обратную связь касанием и нажатие тени кнопок, а также поддержку специальных возможностей.

class RaisedGradientButton extends StatelessWidget {
  final Widget child;
  final Gradient gradient;
  final double width;
  final double height;
  final Function onPressed;
  final borderRadius = BorderRadius.circular(128.0);

  RaisedGradientButton({
    Key key,
    @required this.child,
    Gradient gradient,
    this.width = double.infinity,
    this.height = 50.0,
    this.onPressed,
  })  : this.gradient = gradient ??
            LinearGradient(
              colors: [
                Colors.blue,
                Colors.red,
              ],
              begin: FractionalOffset.centerLeft,
              end: FractionalOffset.centerRight,
            ),
        super(key: key);

  @override
  Widget build(BuildContext context) => Stack(
        children: [
          Positioned.fill(
            child: ClipRRect(
              borderRadius: borderRadius,
              child: Container(
                width: width,
                height: height,
                decoration: BoxDecoration(
                  gradient: gradient,
                ),
              ),
            ),
          ),
          Container(
            width: width,
            height: height,
            child: RaisedButton(
              shape: RoundedRectangleBorder(
                borderRadius: borderRadius,
              ),
              padding: EdgeInsets.zero,
              child: Center(child: child),
              onPressed: onPressed,
              color: Colors.transparent,
            ),
          ),
        ],
      );
}
0 голосов
/ 01 апреля 2019

Если кто-нибудь когда-либо сталкивался с той же проблемой.Вот мой код о том, как я понял это.

class GradientButton extends StatelessWidget {
  final Widget child;

  // final Gradient gradient;
  final double width;
  final double height;
  final bool isEnabled;
  final Function onPressed;

  const GradientButton({
    Key key,
    @required this.child,
    // this.gradient,
    this.isEnabled,
    this.width,
    this.height,
    this.onPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Color _statusColor;
    if (isEnabled != null) {
      // Show gradient color by making material widget transparent
      if (isEnabled == true) {
        _statusColor = Colors.transparent;
      } else {
        // Show grey color if isEnabled is false
        _statusColor = Colors.grey;
      }
    } else {
      // Show grey color if isEnabled is null
      _statusColor = Colors.transparent;
    }

    return Container(
      width: width,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        gradient: LinearGradient(
          colors: [
            Color(0xFF3186E3),
            Color(0xFF1D36C4),
          ],
          begin: FractionalOffset.centerLeft,
          end: FractionalOffset.centerRight,
        ),
      ),
      child: Material(
          shape: RoundedRectangleBorder(
              borderRadius: new BorderRadius.circular(4)),
          color: _statusColor,
          child: InkWell(
              borderRadius: BorderRadius.circular(32),
              onTap: onPressed,
              child: Padding(
                padding: EdgeInsets.fromLTRB(24, 16, 24, 16),
                child: Center(
                  child: child,
                ),
              ))),
    );
  }
}
...