flutter - Как сделать поднятую кнопку с градиентным фоном? - программирование
Подтвердить что ты не робот

flutter - Как сделать поднятую кнопку с градиентным фоном?

Есть ли способ изменить цвет фона приподнятой кнопки на градиент? если нет, как я могу добиться чего-то подобного?

4b9b3361

Ответ 1

Вы можете создать свой собственный

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: gradient, boxShadow: [
        BoxShadow(
          color: Colors.grey[500],
          offset: Offset(0.0, 1.5),
          blurRadius: 1.5,
        ),
      ]),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
            onTap: onPressed,
            child: Center(
              child: child,
            )),
      ),
    );
  }
}

И используйте его в любом месте следующим образом:

RaisedGradientButton(
  child: Text(
    'Button',
    style: TextStyle(color: Colors.white),
  ),
  gradient: LinearGradient(
    colors: <Color>[Colors.green, Colors.black],
  ),
  onPressed: (){
    print('button clicked');
  }
),

Custom button

Далее вы можете поиграть с тенями и закругленными границами, отредактировав свойство оформления контейнера, пока оно не будет соответствовать вашей спецификации.

Ответ 2

Обратитесь ниже -

RaisedButton(
     onPressed: () {},
     textColor: Colors.white,
     padding: const EdgeInsets.all(0.0),
     shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(80.0)),
     child: Container(
       decoration: const BoxDecoration(
         gradient: LinearGradient(
           colors: <Color>[
             Color(0xFF0D47A1),
             Color(0xFF1976D2),
             Color(0xFF42A5F5),
           ],
         ),
         borderRadius: BorderRadius.all(Radius.circular(80.0))
       ),
       padding: const EdgeInsets.fromLTRB(20, 10, 20, 10),
       child: const Text(
           'Gradient Button',
           style: TextStyle(fontSize: 20)
       ),
     ),
   )

Ответ 3

Пакет Gradient доступен в магазине паба, который поддерживает несколько предопределенных градиентов

Вы можете создать кнопку градиента как

GradientButton(
                 child: Text('Gradient'),
                 callback: () {},
                 gradient: Gradients.backToFuture,
           ),

Пакет имеет GradientCard, GradientProgressIndicator, GradientButton, CircularGradientButton и GradientText

Градиентные виджеты

Ответ 4

Просто сделайте еще один контейнер в качестве дочернего, установите оформление этого контейнера и сделайте градиентный цвет, как вы хотите

Затем после этого используйте RaisedButton в качестве дочернего элемента указанного выше контейнера, также как и для MaterialButton.

   child: Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
            colors: [Colors.red, Colors.blue],
            begin: FractionalOffset(0.0, 0.0),
            end: FractionalOffset(0.5, 0.0),
            stops: [0.0, 1.0],
            tileMode: TileMode.clamp),
      ),
      child: RaisedButton(
        color: Colors.transparent,
        child: Text("Ask Permssion"),
        onPressed: () {
          askPermission();
        },
      )),

Выход:

GradientRaisedButton

Ответ 5

RevelyGradient

это библиотека, которая управляет градиентом элементов в android, и я надеюсь, что это поможет вам. :)

Ответ 6

Я знаю, что этот вопрос немного староват. Но я столкнулся с этим требованием и хотел поделиться своим решением. Он использует Card и анимирует высоту при нажатии кнопки.

import 'package:flutter/material.dart';

class GradientButton extends StatefulWidget {
  final String label;
  final VoidCallback onPressed;
  final Gradient gradient;
  final double elevation;
  final double height;
  final TextStyle labelStyle;

  GradientButton({
    @required this.label,
    @required this.onPressed,
    @required this.gradient,
    this.elevation,
    this.height,
    this.labelStyle,
  })  : assert(label != null && onPressed != null),
        assert(gradient != null);

  @override
  _GradientButtonState createState() => _GradientButtonState();
}

class _GradientButtonState extends State<GradientButton> with TickerProviderStateMixin {
  AnimationController _animationController;
  Animation _animation;

  elevateUp(TapDownDetails details) {
    _animationController.forward();
  }

  elevateDown() {
    _animationController.reverse();
  }

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(duration: Duration(milliseconds: 50), vsync: this);
    _animation = Tween(begin: widget.elevation ?? 2.0, end: 12.0).animate(_animationController);
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (c, w) {
        return GestureDetector(
          onTapDown: elevateUp,
          onTapCancel: elevateDown,
          onTapUp: (value) {
            elevateDown();
            widget.onPressed();
          },
          child: Card(
            elevation: _animation.value,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(25.0),
            ),
            child: Container(
              width: double.infinity,
              height: widget.height ?? 50.0,
              decoration: BoxDecoration(
                gradient: widget.gradient,
                borderRadius: BorderRadius.circular(25.0),
              ),
              child: Center(
                child: Text(
                  widget.label,
                  style: widget.labelStyle ?? Theme.of(context).textTheme.button,
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

Есть место для его улучшения (возможно, вам не нужны эти округлые границы по умолчанию), но надежда может быть полезна для некоторых из вас: D

Ответ 7

Вы можете использовать более простой способ, используя RawMaterialButton из material.dart, вы также можете сделать его округлым или округлым. Вот простой пример этого.

  Card(
    elevation: 7,
    child: Container(
      width: 120.0,
      height: 75.0,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.bottomLeft,
          end: Alignment.topRight,
          colors: <Color>[
            Colors.blue,
            Colors.red,
          ],
        ),
      ),
      child: RawMaterialButton(
        onPressed: () {},
        splashColor: Colors.grey,
        child: Text(
          "Button",
          style: TextStyle(color: Colors.white, fontSize: 20.0),
        ),
      ),
    ),
  ),

Ответ 8

Документ API Flutter содержит пример того, как визуализировать RaisedButton с градиентным фоном - см. здесь https://api.flutter.dev/flutter/material/RaisedButton-class.html

Widget gradientButton = Container(
  child: RaisedButton(
    onPressed: () { },
    textColor: Colors.white,
    padding: const EdgeInsets.all(0.0),
    child: Container(
      width: 300,
      decoration: new BoxDecoration(
        gradient: new LinearGradient(
          colors: [
            Color.fromARGB(255, 148, 231, 225),
            Color.fromARGB(255, 62, 182, 226)
          ],
        )
      ),
      padding: const EdgeInsets.all(10.0),
      child: Text(
        "Gradient Button",
        textAlign: TextAlign.center,
      ),
    ),
  ),
);

Gradient Button

Ответ 9

Все вышеприведенное решение не работает без каких-либо незначительных артефактов или проблем (например, отсутствующий эффект ряби, нежелательные границы, несоблюдение минимальной ширины темы для кнопок).

В приведенном ниже решении нет ни одной из перечисленных выше проблем (критической частью является использование виджета Ink для сохранения возможностей пульсации над градиентом):

RaisedButton(
  onPressed: () { },
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(80.0)),
  padding: const EdgeInsets.all(0.0),
  child: Ink(
    decoration: const BoxDecoration(
      gradient: myGradient,
      borderRadius: BorderRadius.all(Radius.circular(80.0)),
    ),
    child: Container(
      constraints: const BoxConstraints(minWidth: 88.0, minHeight: 36.0), // min sizes for Material buttons
      alignment: Alignment.center,
      child: const Text(
        'OK',
        textAlign: TextAlign.center,
      ),
    ),
  ),
)

enter image description here