When building a Flutter application, it is common to have a form with a TextFormField that sends data to an API for validation. In this article, we will show you how to display validation messages in a TextFormField based on the API response.
Prerequisites
To follow this article, you should have a basic understanding of Flutter and how to make HTTP requests. You should also have a server-side API that can validate the data sent from the Flutter application.
Creating a TextFormField
Let's start by creating a simple form with a TextFormField that will send data to the API for validation.
import 'package:flutter/material.dart';
class MyForm extends StatefulWidget {
@override
_MyFormState createState() => _MyFormState();
}
class _MyFormState extends State {
final _formKey = GlobalKey();
String _name;
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
onSaved: (value) => _name = value,
decoration: InputDecoration(labelText: 'Name'),
),
RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
// Send data to API for validation
}
},
child: Text('Submit'),
),
],
),
);
}
}
In the example above, we have a simple form with a TextFormField that has a validation function. If the text is empty, it will display a message saying "Please enter some text".
Sending Data to API for Validation
Now that we have a form with a TextFormField, we need to send the data to the API for validation. We can use the http package to make HTTP requests.
import 'package:http/http.dart' as http;
void sendDataToApi(String name) async {
final response = await http.post(
'https://my-api.com/validate',
headers: {'Content-Type': 'application/json'},
body: json.encode({'name': name}),
);
if (response.statusCode == 200) {
// Validation successful
} else {
// Validation failed
}
}
In the example above, we have a function called sendDataToApi that sends a POST request to our API. The name parameter is the data that we want to validate.
Displaying Validation Messages
Now that we have sent the data to the API, we need to display the validation message in the TextFormField. We can do this by updating the validation function in the TextFormField.
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
if (!_apiResponse.isValid) {
return _apiResponse.message;
}
return null;
},
In the example above, we have updated the validation function to check the _apiResponse.isValid property. If the validation fails, it will display the message returned from the API.
We can update the sendDataToApi function to send the validation message back to the Flutter application.
void sendDataToApi(String name) async {
final response = await http.post(
'https://my-api.com/validate',
headers: {'Content-Type': 'application/json'},
body: json.encode({'name': name}),
);
if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);
final apiResponse = ApiResponse.fromJson(jsonResponse);
setState(() {
_apiResponse = apiResponse;
});
}
}
In the example above, we have updated the sendDataToApi function to send the validation message back to the Flutter application. We are using a ApiResponse class to parse the JSON response from the API.
class ApiResponse {
final bool isValid;
final String message;
ApiResponse({this.isValid, this.message});
factory ApiResponse.fromJson(Map json) {
return ApiResponse(
isValid: json['isValid'],
message: json['message'],
);
}
}
In the example above, we have created a ApiResponse class that parses the JSON response from the API. We are using the factory constructor to create an instance of the class.
In this article, we have shown you how to display validation messages in a TextFormField based on the API response. You can use this technique to validate any data sent from your Flutter application to the API.
References
| Title | URL |
|---|---|
| Flutter - Forms | https://flutter.dev/docs/cookbook/forms/validation |
| Flutter - HTTP | https://flutter.dev/docs/cookbook/networking/fetch-data |