How to change TextField Background Color in Flutter
The TextField widget is one of the most used widgets in Flutter. Hence, proper styling of the TextField is important. In this blog post, let’s learn how to set the background color for TextField in Flutter.
We can customize the looks of TextField using its decoration property and the InputDecoration class. In order to change the background color, we should use the filled property and fillColor property together.
See the code snippet given below.
TextField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
filled: true,
fillColor: Colors.yellowAccent),
controller: _controller,
onSubmitted: (String value) {
debugPrint(value);
},
)
Then you will get the output of TextField with a yellow background.
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 Background Color'),
),
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(),
filled: true,
fillColor: Colors.yellowAccent),
controller: _controller,
onSubmitted: (String value) {
debugPrint(value);
},
)));
}
}
That’s how you change the TextField background color in Flutter.
If you want to change the TextField border color, see this tutorial.