How to Add Borders to TextField in Flutter
Every Flutter developer knows the importance of the TextField widget. Having borders around TextField can make the component significant. In this tutorial, let’s learn how to set borders for TextField in Flutter.
By default, TextField doesn’t have any borders. You can style TextField using the InputDecoration class. The OutlineInputBorder class helps you to add borders around the TextInput easily.
See the code snippet given below.
TextField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter your name',
),
controller: _controller,
onSubmitted: (String value) {
debugPrint(value);
},
)
You will get the following output.
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 Border'),
),
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: TextField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter your name',
),
controller: _controller,
onSubmitted: (String value) {
debugPrint(value);
},
),
));
}
}
See how to change the TextField border color here.
That’s how you add borders to the TextField widget. I hope this tutorial is helpful for you.