How to add TextField Elevation in Flutter

The elevation is an important feature in material design. By default, TextField doesn’t have any elevation. But in some cases, you may want to add elevation to TextField in Flutter.

The TextField widget doesn’t have any properties to add elevation. So, the easy way to create shadows is to wrap the TextField widget using the Material widget.

See the following code snippet.

Material(
                elevation: 10,
                child: TextField(
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                  ),
                  controller: _controller,
                  onSubmitted: (String value) {
                    debugPrint(value);
                  },
                )

The Material widget has an elevation property to add elevation to the child.

Following is the output of TextField with elevation.

Flutter textfield elevation

Following is the complete code.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Flutter TextField Elevation'),
        ),
        body: const MyStatefulWidget());
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  late TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
        child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Material(
                elevation: 10,
                child: TextField(
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                  ),
                  controller: _controller,
                  onSubmitted: (String value) {
                    debugPrint(value);
                  },
                ))));
  }
}

That’s how you add elevation to the TextField in Flutter.

Leave a Comment