为何为sqflite包设置别名后Android Studio无法识别firstIntValue函数?
问题:为sqflite包设置别名后,无法识别firstIntValue函数
可正常运行的代码
import 'package:sqflite/sqflite.dart'; Future<int> localDBQueryRowCount({required sqf.Database db, required String table}) async { final results = await db.rawQuery('SELECT COUNT(*) FROM $table'); return Sqflite.firstIntValue(results) ?? 0; }
无法运行的代码
import 'package:sqflite/sqflite.dart' as sqf; Future<int> localDBQueryRowCount({required sqf.Database db, required String table}) async { final results = await db.rawQuery('SELECT COUNT(*) FROM $table'); return sqf.firstIntValue(results) ?? 0; // 错误:函数'firstIntValue'未定义 }
原因分析
firstIntValue是sqflite库中的全局顶级函数,并非属于sqf别名对应的命名空间成员。当使用as sqf给库设置别名时,全局函数不会被纳入该别名空间,因此直接用sqf.firstIntValue会找不到这个函数。
而无别名导入时,Sqflite.firstIntValue调用的是Sqflite类的静态方法(sqflite库同时提供了全局函数和类静态方法两种调用方式),所以可以正常运行。
解决办法
有两种修复方式:
- 直接调用全局的
firstIntValue,无需添加别名前缀:return firstIntValue(results) ?? 0; - 通过别名访问
Sqflite类的静态方法:return sqf.Sqflite.firstIntValue(results) ?? 0;
内容的提问来源于stack exchange,提问作者TheMortiestMorty
相关产品推荐
相关产品推荐

