flutter_mbtiles_extractor 0.1.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 65

flutter_mbtiles_extractor #

Basic plugin to extract the data (png tiles) from an .mbtiles file and automatically create the folder structure (../folder_name/{z}/{x}/{y}.png).


Installation #

Import the dependency in the dart file you will use it.

   import 'package:flutter_mbtiles_extractor/mbtiles_extractor.dart';

In Android you need to add permissions to read and write in the storage of the device. In your project add the following lines to your AndroidManifest.xml file in your project's Android folder.

       <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
       <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Remember that on API 23 and later you need to ask to the user to grant access for this permissions.

How to use #

In the following example you can see how to realize a extraction of one file.

ExtractResult extractResult = await MBTilesExtractor.extractMBTilesFile(
        "${dir.path}/volcan_villarica.mbtiles", //This is the name of the file i was testing.
          desiredPath: "${dir.path}/tiles/", //Example of final folder
          requestPermissions: true, //This is for Android 6.0+
          removeAfterExtract: true, //Deletes the +.mbtiles file after the extraction is completed
          stopOnError: true, //Stops is one tile could not be extracted
          returnReference: true, //Returns the list of tiles once the extraction is completed
          onlyReference: false, //If true the reference of tiles is returned but the extraction is not performed

The extraction will return an instance of ExtractResult that contains a code and data. The code determinate the extraction result and could be checked using the isSuccessful() function in ExtractResult class or could be done manually.

    if (extractResult.code == ExtractResult.RESULT_FILE_CORRUPT) {
      //The file could not be read because it was damaged

If the file was extracted successfully the data will contain the path to the folder where the tiles are stored.

    if (extractResult.isSuccessful()) {
        var folder= extractResult.data;
        //Do something

Progress can be tracked adding a callback as follows.

ExtractResult extractResult = await MBTilesExtractor.extractMBTilesFile(
        "${dir.path}/volcan_villarica.mbtiles", //This is the name of the file i was testing.
          desiredPath: "${dir.path}/tiles/", //Example of final folder
          onProgress: (total, progress) { // Progress callback
              var percent = progress / total;
              if (percent == 1.0) {
              } else {
                this.progress.value = percent;
              print("Extraction progress: ${(percent * 100).toStringAsFixed(2)}");

Extra info #

This plugin uses the extracted folder to generate a Google Maps like map so you could make a project that uses offline maps.


The Android part use a library to read the .mbtiles file. The original project for Java:


And the Android version:


NOTE: I included a compiled .jar of this library since it don't exist in Maven or JitPack (at least i couldn't find it). Consider update it if exists a new version.

Changelog #

0.1.0 #

  • Migration to Android X.
  • Updated the Gradle and Kotlin plugins.
  • Updated the progress system.
  • Updated documentation.

0.0.7 #

  • Fix: Progress callback now updates the progress even if the reference is not being returned;
  • Updated Android dependencies.

0.0.6 #

  • Added progress callback to the extraction. (Thanks to @kengu)
  • Added documentation to MBTilesExtractor class.

0.0.5 #

  • Added support for XYZ or TMS tile extraction schema. (Thanks to @kengu)
  • Example updated to display the schema update. (Thanks to @kengu)
  • Updated example dependencies.

0.0.4 #

  • Quick fix. A crash was produced when extracting the metadata of an incomplete mbtiles file.

0.0.3 #

  • Revision on imports

0.0.2 #

  • Added asynchronous working so the extraction doesn't freeze the UI while working.

  • Updated the example

0.0.1 #

  • First release with basic functionality for extracting the tiles from a .mbtiles file.


import 'dart:async';
import 'dart:collection';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_document_picker/flutter_document_picker.dart';
import 'package:flutter_mbtiles_extractor/flutter_mbtiles_extractor.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  _MyAppState createState() => new _MyAppState();

class _MyAppState extends State<MyApp> {
  String _extractionStatus = 'Select a file to extract';
  bool _isBusy = false;
  File _selectedFile;
  Set<String> inProgress = HashSet<String>();
  ValueNotifier progress = ValueNotifier<double>(0.0);

  void initState() {

  Widget build(BuildContext context) {
    List<Widget> widgets = [];
        'Extraction Status:\n $_extractionStatus\n',
        textAlign: TextAlign.center,
          ? Padding(
              padding: EdgeInsets.all(16.0),
              child: AnimatedBuilder(
                animation: progress,
                builder: (context, _) {
                  return Container(
                    child: LinearProgressIndicator(
                      value: progress.value,
          : MaterialButton(
              onPressed: () {
                if (_selectedFile == null || !_selectedFile.existsSync()) {
                } else {
              child: Text(_selectedFile != null ? "Extract" : "Select File"),
              color: Colors.blue,
    if (_selectedFile != null && !_isBusy) {
        onPressed: () {
        child: Text("Deselect File"),
        color: Colors.red,
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('MBTilesExtractor example app'),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: widgets,

  void _startProgress() {
    _isBusy = true;
    progress.value = null;

  void _stopProgress() {
    _isBusy = false;
    progress.value = null;

  Future<void> _extractMBTilesFile() async {
    String result;
    StreamSubscription<dynamic> subscription;
    try {
      //Get directory of the application. This way works best for iOS.
      //The main point here is that the origin of the file is not relevant,
      //as long as you have access to the file.
      //Add path_provider dependency in example/pubspec.yaml to use the next function
      setState(() {
        _extractionStatus = "Extracting... Please wait!";

      Directory appDirectory = await getApplicationDocumentsDirectory();
      ExtractResult extractResult = await MBTilesExtractor.extractMBTilesFile(
        //Path of the selected file.
        //Path of the extraction folder.
        desiredPath: appDirectory.path,
        //Vital in android.
        requestPermissions: true,
        //Deletes the *.mbtiles file after the extraction is completed.
        removeAfterExtract: false,
        //Stops is one tile could not be extracted.
        stopOnError: true,
        //Returns the list of tiles once the extraction is completed.
        returnReference: true,
        //If true the reference of tiles is returned but the extraction is not performed.
        onlyReference: false,
        //The schema of the mbtiles file.
        schema: Schema.XYZ,
        //Progress update callback
        onProgress: (total, progress) {
          var percent = progress / total;
          if (percent == 1.0) {
          } else {
            this.progress.value = percent;
          print("Extraction progress: ${(percent * 100).toStringAsFixed(2)}");
      result = """
      Result Code = ${extractResult.code}
      Extraction Message = ${extractResult.data}
      Tile Count = ${extractResult.tiles.length}
      Metadata = ${extractResult.metadata.toMap()}
      *Tile count only is displayed if reference is being returned
    } catch (ex, st) {
    setState(() {
      _extractionStatus = "$result";


  void _launchFilePicker() async {
    File file;
    String message = "Selection Cancelled";
    setState(() {
    try {
      FlutterDocumentPickerParams params = FlutterDocumentPickerParams(
        allowedFileExtensions: ['mbtiles'],
        allowedUtiTypes: ['cl.ceisufro.fluttermbtilesextractor.mbtiles'],
      final filePath = await FlutterDocumentPicker.openDocument(params: params);
      if (filePath != null && filePath.isNotEmpty) {
        String extension = path.extension(filePath);
        if (extension == ".mbtiles") {
          file = File(filePath);
          message = "Ready to extract";
        } else {
          message = "Selected file is not mbtiles";
    } catch (ex) {
      message = "Selected file is not mbtiles";
    } finally {
      setState(() {
        this._extractionStatus = message;
        this._selectedFile = file;

  void _clearSelectedFile() {
    setState(() {
      this._selectedFile = null;
      this._extractionStatus = "File de-selected. Select a file to extract";

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  flutter_mbtiles_extractor: ^0.1.0

2. Install it

You can install packages from the command line:

with Flutter:

$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:flutter_mbtiles_extractor/flutter_mbtiles_extractor.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on Apr 4, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Health suggestions

Format lib/src/extract_request.dart.

Run flutter format to format lib/src/extract_request.dart.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.28.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8