I am trying to hide/show a TextField in a Flutter application based on a comparation between 2 dates, but this condition always throws an error FormatException: Trying to read yyyy from at position 0.
If I comment out the condition, there is no error.
The date I am trying to parse is 2022-10-11
My global variables:
String validityString = '';
DateTime currentDate = DateUtils.dateOnly(DateTime.now());
DateTime thisValidity =
Intl.withLocale('en', () => DateFormat("yyyy-MM-dd").parse(validityString));
This is where I assign the date:
if (response.data["status"] == "success") {
setState(() {
name = json.encode(response.data["data"]["name"]);
credit = json.encode(response.data["data"]["credit"]);
currency = json.encode(response.data["data"]["currency"]);
entryCount = json.encode(response.data["data"]["entryCount"]);
validity = json.encode(response.data["data"]["validity"]);
validityString = validity.toString().replaceAll(RegExp('"'), '');
});
The condition is here:
if (thisValidity.isBefore(currentDate))
TextField(
readOnly: true,
enabled: false,
decoration: InputDecoration(
labelText:
AppLocalizations.of(context)!.validity +
validity
.toString()
.replaceAll(RegExp('"'), ''),
border: const OutlineInputBorder(),
labelStyle: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold),
filled: true,
fillColor: Colors.amberAccent,
),
),
Now if I do some logging, without the condition in use it will show me the correct data, but once I uncomment it, it will throw the mentioned error. I tried to all different positions to put my variables or date formatting, but no luck so far.
Any tips or help will be appriciated. :)
Because you are using validityString inside
which is empty right now and get a value latter when
will get execute. And after that you have not recalculate thisValidity
So in the end, you are comparing an empty string and date and that empty string cannot get parsed by the Datetime class here.