I have defined a custom widget in flutter(version 3.7.11
) like this:
// ignore_for_file: prefer_typing_uninitialized_variables
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hexcolor/hexcolor.dart';
class MyTextField extends StatelessWidget {
final controller;
final String hintText;
final bool obscureText;
final Icon prefixIcon;
final Function()? onChanged;
const MyTextField(
{super.key,
required this.controller,
required this.hintText,
required this.obscureText,
required this.prefixIcon,
this.onChanged});
@override
Widget build(BuildContext context) {
return TextField(
controller: controller,
obscureText: obscureText,
cursorColor: HexColor("#4f4f4f"),
decoration: InputDecoration(
hintText: hintText,
fillColor: HexColor("#f0f3f1"),
contentPadding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
hintStyle: GoogleFonts.poppins(
fontSize: 15,
color: HexColor("#8d8d8d"),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: BorderSide.none,
),
prefixIcon: prefixIcon,
prefixIconColor: HexColor("#4f4f4f"),
filled: true,
),
);
}
}
and I am using this widget like this:
import 'package:flutter/material.dart';
import 'package:untitled4/my_textfield.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
void validatePhone() {
print("object");
}
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(body:
SafeArea(
child:MyTextField(
controller: null,
onChanged: ()=>validatePhone(),
hintText: 'dddd',
obscureText: false,
prefixIcon: const Icon(Icons.phone_android_outlined)
)
)),
);
}
}
now I found the MyTextField
event did not trigger onchange event. why did this happen? Am I missing something? what should I do to fixed this issue? this is the dependencies I am using:
hexcolor: ^3.0.1
google_fonts: ^3.0.1
2
Answers
You need to set the onChanged parameter of the TextField. like this
To call that function inside TextFields onChanged method write this way,