我想在 Flutter 中将 String 转换为 TextInputType 数据类型
我将每个文本表单字段的输入类型上传到 firestore,但它不接受 TextInputType 作为数据类型,所以我将其转换为 String
有人可以告诉如何将字符串转换为 TextInputType
您可以创建一个自定义方法来执行此操作。例如,你可以有这样的东西,它将你的字符串转换为相应的输入类型:
TextInputType textInputTypeFromString(String input) {
switch (input) {
case 'text':
return TextInputType.text;
case 'multiline':
return TextInputType.multiline;
case 'number':
return TextInputType.number;
case 'phone':
return TextInputType.phone;
case 'datetime':
return TextInputType.datetime;
case 'emailAddress':
return TextInputType.emailAddress;
case 'url':
return TextInputType.url;
case 'visiblePassword':
return TextInputType.visiblePassword;
default:
return TextInputType.text;
}
}
另一种选择是使用映射而不是使用此开关,将字符串作为键,将 TextInputType 作为值并直接访问:
final Map<String, TextInputType> inputTypeMap = {
'text': TextInputType.text,
'multiline': TextInputType.multiline,
'number': TextInputType.number,
'phone': TextInputType.phone,
'datetime': TextInputType.datetime,
'emailAddress': TextInputType.emailAddress,
'url': TextInputType.url,
'visiblePassword': TextInputType.visiblePassword,
};
TextInputType textInputTypeFromString(String input) {
return inputTypeMap[input] ?? TextInputType.text;
}