Flutter-如何在焦点上的TextFormField中添加阴影

时间:2020-03-05 12:48:03

标签: flutter flutter-widget

在Flutter中聚焦时,如何在TextFormField中添加阴影?我希望该字段具有这种外观:

field with shadow

到目前为止,我在对焦时设法应用了边框,但是我看不到任何应用阴影的选项:

TextFormField(
  decoration: InputDecoration(
      fillColor: Colors.white,
      hoverColor: Colors.white,
      filled: true,
      enabledBorder: OutlineInputBorder(borderSide: BorderSide.none),
      focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Colors.grey, width: 1))),
);

关于如何获得这种效果的任何想法?

2 个答案:

答案 0 :(得分:3)

重要:用TextField小部件包装Form并分配_formKey 它有助于防止在setState()

之后关闭键盘

完整示例:

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: Home(),
      ),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  static GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  FocusNode focusNode;

  @override
  void initState() {
    super.initState();
    focusNode = FocusNode();
    focusNode.addListener(() => setState(() {}));
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: Duration(seconds: 5),
      margin: const EdgeInsets.all(16),
      decoration: focusNode.hasFocus ? BoxDecoration(boxShadow: [BoxShadow(blurRadius: 6)]) : null,
      child: Form(
        key: _formKey,
        child: TextFormField(
          focusNode: focusNode,
          decoration: InputDecoration(
              fillColor: Colors.white,
              hoverColor: Colors.white,
              filled: true,
              enabledBorder: OutlineInputBorder(borderSide: BorderSide.none),
              focusedBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.grey, width: 1))),
        ),
      ),
    );
  }
}

https://imgur.com/a/9vcdvoM

答案 1 :(得分:0)

尝试一下:

 Container(
            decoration: BoxDecoration(
              boxShadow:  [new BoxShadow(
                color: Colors.black,
                blurRadius: 5.0, // You can set this blurRadius as per your requirement
              ),]
            ),
            child: TextFormField(
              decoration: InputDecoration(
                  fillColor: Colors.white,
                  hoverColor: Colors.white,
                  filled: true,
                  enabledBorder: OutlineInputBorder(borderSide: BorderSide.none),
                  focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.grey, width: 1))),
            ),
          ),