You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何用类似SQL LIKE的条件校验选中的.db文件名?

解决FilePicker选中.db文件的校验问题

你当前的判断条件result.names == ['*.db']不成立的原因是:result.names返回的是选中文件的实际文件名数组(比如选中test.db时会返回['test.db']),和通配符数组['*.db']完全不匹配,自然无法触发校验逻辑。

要实现类似SQL LIKE '%.db'的校验效果,直接检查文件名是否以.db结尾即可,具体修改如下:

onTap: () async {
  var databasesPath = await getDatabasesPath();
  var dbPath = join(databasesPath, 'ledger.db');
  print('dbPath $dbPath');
  
  FilePickerResult? result = await FilePicker.platform.pickFiles(
    type: FileType.any,
    // 如果FileType.custom可用,也可以尝试开启下面两行,提前过滤文件类型
    // type: FileType.custom,
    // allowedExtensions: ['db'],
  );
  
  print('result ${result?.names}');
  
  if (result != null) {
    // 获取选中的单个文件名
    String selectedFileName = result.files.single.name;
    // 校验文件名是否以.db结尾
    if (selectedFileName.endsWith('.db')) {
      File source = File(result.files.single.path!);
      await source.copy(dbPath);
      print('Successfully Restored DB');
    } else {
      print('请选择.db格式的数据库文件');
    }
  } else {
    print('未选择任何文件');
  }
},

额外说明

  • 如果FileType.custom配合allowedExtensions: ['db']可以正常使用,建议优先开启,这样在文件选择器层面就会过滤非.db文件,减少后续校验逻辑的必要性。
  • 若必须使用FileType.any,上述的endsWith('.db')校验可以确保只有后缀为.db的文件才会执行复制操作,避免非.db文件导致数据库崩溃。

内容的提问来源于stack exchange,提问作者Abdullah Bahattab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:05:25