Reputation: 159
I'm a beginner in flutter, i want to use SQlite database using sqflite package in my Flutter App,
I'm running my flutter app on chrome because I have the emulator not working, I use getApplicationDocumentsDirectory
in the code and i have an error saying :
Error: MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)
I read in a post: I ran into this after starting to add web support to an application. The getApplicationDocumentsDirectory function only supports iOS and Android (docs). I added a check for web and changed the way I set the directory which fixed the "No implementation found for method" for me.
To tell if the platform is web use Flutter's kIsWeb:
Then handle setting the directory accordingly:
if (kIsWeb) {
// Set web-specific directory
} else {
appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
}
but i don't know how to Set web-specific directory.
My code is
if (_database != null) {
return _database;
}
_database = await _initializeDatabase();
return _database;
}
Future<Database> _initializeDatabase() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = join(directory.path, 'annonce_database.db');
return await openDatabase(path, version: _dbVersion, onCreate: _onCreate);
}```
Upvotes: 11
Views: 15162
Reputation: 7746
Faced the same issue.
Web Build Error: Uncaught (in promise) Error: MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)
Actual Code
final appDocDir = await getApplicationDocumentsDirectory();
// Initialize hive.
await Hive.initFlutter();
// Register Adapters.
Hive
..init(appDocDir.path)
..registerAdapter(ActivityAdapter())
..registerAdapter(ActivityTypeModelAdapter());
After Fixing it with kIsWeb
var path = "/assets/db";
if (!kIsWeb) {
var appDocDir = await getApplicationDocumentsDirectory();
path = appDocDir.path;
}
// Initialize hive.
await Hive.initFlutter();
// Register Adapters.
Hive
..init(path)
..registerAdapter(ActivityAdapter())
..registerAdapter(ActivityTypeModelAdapter());
Upvotes: 4
Reputation: 455
getApplicationDocumentsDirectory() doesn't works on Web, so using your code, you have to modify th _initializeDatabase() function, and replace with a String path route in order to use it in Web (i.e. assets folder inside the project) Don't forget to import KIsWeb
import 'package:flutter/foundation.dart' show kIsWeb;
...
Future<Database> _initializeDatabase() async {
//here
if (kIsWeb) {
String path = "/assets/db";
} else {
Directory directory = await getApplicationDocumentsDirectory();
String path = join(directory.path, 'annonce_database.db');
}
return await openDatabase(path, version: _dbVersion, onCreate: _onCreate);
}
Upvotes: 7