传递version至onCreate方法并使用int类型ID查询数据库时遇'int isn't a type'错误
Let's break down the problems in your code and fix them step by step:
1. Root Cause: Method Name Conflict with Built-in Type
The main issue throwing the "int isn't a type" error is that you named a method int()—this directly conflicts with Dart's built-in int type. When you try to use int as a type in the onCreate callback parameter, Dart gets confused and thinks you're referring to your method instead of the integer type.
Fix: Rename the method to something valid like initDatabase() or openDb().
2. Invalid whereArgs Type
In your fetchItem method, whereArgs expects a List of values, but you're passing a Set ({id}). This will trigger a type mismatch error when you run the query.
Fix: Change {id} to [id] to use a List instead of a Set.
3. Incomplete CREATE TABLE Statement
Your CREATE TABLE query is empty—you need to define at least one column (like the id you're using in fetchItem). Without columns, the database table creation will fail immediately.
Fix: Add columns to the table definition, e.g., id INTEGER PRIMARY KEY AUTOINCREMENT (adjust based on your actual data needs).
Corrected Code
Here's the fully fixed version of your class with all these adjustments:
import 'dart:io'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; import 'package:path_provider/path_provider.dart'; class NewsDbProvider { Database? db; // Mark as nullable to comply with Dart null safety // Renamed from int() to initDatabase() to avoid type conflict Future<void> initDatabase() async { Directory documentsDirectory = await getApplicationDocumentsDirectory(); final path = join(documentsDirectory.path, "items.db"); db = await openDatabase( path, version: 1, onCreate: (Database newDb, int version) { newDb.execute(""" CREATE TABLE Items ( id INTEGER PRIMARY KEY AUTOINCREMENT, -- Add your custom columns here, for example: title TEXT NOT NULL, content TEXT ) """); }, ); } Future<List<Map<String, dynamic>>?> fetchItem(int id) async { if (db == null) return null; // Guard clause for uninitialized database return db!.query( "Items", columns: null, // Fetches all columns where: 'id = ?', whereArgs: [id], // Fixed to use a List ); } }
Additional Notes
- I added a nullable type (
Database?) fordbsince it's initialized asynchronously—this prevents null safety errors in Dart. - The guard clause in
fetchItemhandles cases where the database hasn't been initialized yet (you should always callinitDatabase()before using any database operations).
内容的提问来源于stack exchange,提问作者user8273163

