Flutter 中可以使用 try-catch 语句来判断字符串是否可以转换为时间或数字类型。

判断字符串是否可以转换为时间类型:

String timeString = '2022-01-01 12:00:00';
try {
  DateTime dateTime = DateTime.parse(timeString);
  print('时间格式正确');
} catch (e) {
  print('时间格式错误');
}

判断字符串是否可以转换为数字类型:

String numberString = '123';
try {
  int number = int.parse(numberString);
  print('数字格式正确');
} catch (e) {
  print('数字格式错误');
}

需要注意的是,如果字符串格式不正确,会抛出异常。可以在 catch 语句中对异常进行处理。

Flutter 字符串类型判断:时间和数字

原文地址: https://www.cveoy.top/t/topic/kGzS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录