We going to use OutlinedButton
and DecoratedBox
to develop the button with a custom shadow.
DecoratedBox
is a widget that paints a Decoration
either before or after its child paints. Pay attention that Container
insets its child by the widths of the borders – this widget does not.
Constructor of DecoratedBox
:
DecoratedBox({ Key? key, required Decoration decoration, DecorationPosition position = DecorationPosition.background, Widget? child })
OutlinedButton
is a Material Design “Outlined Button”. Essentially a TextButton
with an outlined border.
Constructor of OutlinedButton
:
OutlinedButton({ Key? key, required VoidCallback? onPressed, VoidCallback? onLongPress, ValueChanged<bool>? onHover, ValueChanged<bool>? onFocusChange, ButtonStyle? style, FocusNode? focusNode, bool autofocus = false, Clip clipBehavior = Clip.none, MaterialStatesController? statesController, required Widget? child })
Example of how it looks:
Full code:
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Button Shadow'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { bool _isShadow = true; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, children: const [ Text( 'Button Shadow', ) ], ), Padding( padding: const EdgeInsets.only(top: 20.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ DecoratedBox( decoration: BoxDecoration( boxShadow: _isShadow ? [ BoxShadow( color: Colors.black.withOpacity(0.2), spreadRadius: 6, blurRadius: 20, offset: const Offset(0, 3), ) ] : []), child: OutlinedButton( style: const ButtonStyle( backgroundColor: MaterialStatePropertyAll(Colors.white), ), onPressed: () { setState(() { _isShadow = !_isShadow; }); }, child: Text( _isShadow ? 'Disable shadow' : 'Enable shadow', style: const TextStyle(color: Colors.black), )), ) ], ), ) ], ), ), ); } }