Search code examples
flutterdartuser-interfacematerial-designtextfield

How to change cursor color in TextField Flutter


I'm facing the problem that my cursor color isn't changing when wrapping TextField by Theme widget.


Solution

  • The main problem here is that pointer color isn't changing while wrapping directly. It's mentioned in this thread https://github.com/flutter/flutter/issues/74890

    What you can do, is add Theme in your MaterialApp widget

      Widget build(BuildContext context) {
        return MaterialApp(
          theme: ThemeData(
            textSelectionTheme: TextSelectionThemeData(
              selectionColor: Colors.green,
              cursorColor: Colors.green,
              selectionHandleColor: Colors.green,
            ),
          ),
          home: const HomeWidget(),
        );
      }
    

    and your TextField will look like this:

    class _SimpleTextFieldState extends State<SimpleTextField> {
      Color focusColor = Colors.grey;
    
      @override
      Widget build(BuildContext context) {
        return Focus(
          onFocusChange: (hasFocus) {
            if (hasFocus) {
              focusColor = Colors.green;
            } else {
              focusColor = Colors.grey;
            }
            setState(() {});
          },
          child: TextField(
            decoration: InputDecoration(
              isDense: true,
              labelText: 'Text',
              labelStyle: TextStyle(
                color: focusColor,
                fontSize: fontSize15,
              ),
              enabledBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.grey),
              ),
              focusedBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.green),
              ),
              border: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.green),
              ),
            ),
            style: TextStyle(
              color: Colors.white,
              fontSize: fontSize15,
            ),
          ),
        );
      }
    }
    

    inactive

    PriceField inactive

    active

    PriceField active