How to change TextField Focus Border Color in Flutter

TextField is a very important widget in Flutter. Showing borders around TextField make it distinct and beautiful. In this tutorial, let’s learn how to change the TextField border color when it is focused.

You can add borders to the TextField using the InputDecoration class. The focusedBorder property of the OutlineInputBorder class can be used to change the color of the focussed border.

See the code snippet given below.

TextField(
        decoration: const InputDecoration(
          enabledBorder: OutlineInputBorder(),
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.red, width: 2.0),
          ),
        ),
        controller: _controller,
        onSubmitted: (String value) {
          debugPrint(value);
        },
      )

Then you will get an output of the TextField with a red color border when focussed.

flutter textfield focus border color

Following is the complete code to change the border color.

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 Focussed Border 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(
          enabledBorder: OutlineInputBorder(),
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.red, width: 2.0),
          ),
        ),
        controller: _controller,
        onSubmitted: (String value) {
          debugPrint(value);
        },
      ),
    ));
  }
}

That’s how you change the border color of TextField when it is focused.

Similar Posts

Leave a Reply