I'm trying to call this widget which contains FormField
with it's validator as a variable.
import 'package:flutter/material.dart';
class InputField extends StatelessWidget {
final String label, label2;
final String content, content2;
var fieldController = TextEditingController();
void fieldValidator =() {
};
InputField(
{this.label,
this.content,
this.label2,
this.content2,
this.fieldValidator
});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: Container(
width: 50.0,
child: Text(
"$label",
textAlign: TextAlign.left,
style: TextStyle(
fontWeight: FontWeight.w900,
color: Color.fromARGB(255, 255, 255, 255),
),
),
),
),
SizedBox(
width: 5.0,
),
Expanded(
flex: 3,
child: Container(
width: MediaQuery.of(context).size.width / 3.7,
color: Color.fromARGB(255, 255, 255, 255),
child: TextFormField(
controller: fieldController,
validator: fieldValidator,
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
),
decoration: InputDecoration(
contentPadding: EdgeInsets.all(10.0),
hintText: "$content",
hintStyle: TextStyle(
color: Color.fromARGB(255, 190, 190, 190),
fontSize: 14),
fillColor: Color.fromARGB(255, 0, 0, 0),
),
),
),
),
],
);
},
);
}
}
I'm setting the validator in the widget constractor , and I want to give my own validator function every time I call the widget like this :
InputField( label: "City",
content: "Please provide us your city name",
fieldValidator:(value) {
if (value == null || value.isEmpty) {
return 'This one is required';
}
return null;
},),
I'm getting this error on the first page where I created my widget:
This expression has a type of 'void' so its value can't be used.
Try checking to see if you're using the correct API; there might be a function or call that returns void you didn't expect. Also check type parameters and variables which might also be void.
CodePudding user response:
the validator should be from the type of FormFieldValidator<String>?
instead of void
so your validator should look like:
FormFieldValidator<String>? fieldValidator =(fieldValue) {
return "result";
};
CodePudding user response:
If you look at the TextFormField
, you will see that validator
is defined like this, a function that may receive a String and returns another.
String? Function(String?)? validator
I would suggest that you make the same for your fieldValidator
, so that your InputField
definition would look like this:
class InputField extends StatelessWidget {
final String label, label2;
final String content, content2;
final String Function(String?)? fieldValidator;
var fieldController = TextEditingController();
...