Articles in this section
Category / Section

How to load data from offline SQLite database to Flutter Calendar?

4 mins read

Flutter Calendar allows you to access the local database using SQLite. You can go through the following steps to load the offline data to calendar events.

STEP 1: Add the required packages in the dependencies of pubspec.yaml.   

syncfusion_flutter_calendar: 18.4.39
sqflite: ^1.3.2+3
path_provider: ^1.6.27
intl: ^0.16.0
http: "0.11.3+17"
date_format: ^1.0.8
connectivity: ^0.3.0

STEP 2: Add the database_helper.dart and create the database using the DatabaseHelper instance.

static final table = 'flutter_calendar_events';
 
static final columnId = '_id';
static final columnName = 'name';
static final columnStart = 'start';
static final columnEnd = 'end';
 
// make this a singleton class
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
 
// only have a single app-wide reference to the database
static Database _database;
Future<Database> get database async {
  if (_database != null) return _database;
  // lazily instantiate the db the first time it is accessed
  _database = await _initDatabase();
  return _database;
}
_initDatabase() async {
  Directory documentsDirectory = await getApplicationDocumentsDirectory();
  String path = join(documentsDirectory.path,”flutter_calendar_database.db”);
  return await openDatabase(path,
      version: _databaseVersion,
      onCreate: _onCreate);
}

STEP 3: Create the database table using Create Table query.

// SQL code to create the database table
Future _onCreate(Database db, int version) async {
  await db.execute('''
        CREATE TABLE $table (
          $columnId INTEGER PRIMARY KEY,
          $columnName TEXT NOT NULL,
          $columnStart TEXT NOT NULL,
          $columnEnd TEXT NOT NULL
        )
        ''');
}

STEP 4: Add the helper methods for add, remove, update operations.

Future<int> insert(Map<String, dynamic> row) async {
  Database db = await instance.database;
  return await db.insert(table, row);
}
 
// All of the rows are returned as a list of maps, where each map is
// a key-value list of columns.
Future<List<Map<String, dynamic>>> queryAllRows() async {
  Database db = await instance.database;
  return await db.query(table);
}
 
// All of the methods (insert, query, update, delete) can also be done using
// raw SQL commands. This method uses a raw query to give the row count.
Future<int> queryRowCount() async {
  Database db = await instance.database;
  return Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM $table'));
}
 
// We are assuming here that the id column in the map is set. The other
// column values will be used to update the row.
Future<int> update(Map<String, dynamic> row) async {
  Database db = await instance.database;
  int id = row[columnId];
  return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
}
 
// Deletes the row specified by the id. The number of affected rows is
// returned. This should be 1 as long as the row exists.
Future<int> delete(int id) async {
  Database db = await instance.database;
  return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
}
 
Future<List> getAllRecords(String dbTable) async {
  var dbClient = await instance.database;
  var result = await dbClient.rawQuery("SELECT * FROM $dbTable");
 
  return result.toList();
}

STEP 5: In initState(), set the default values for Calendar.

DatabaseHelper dbHelper = DatabaseHelper.instance;
List<Color> _colorCollection;
List<String> _views;
 
@override
void initState() {
  _initializeEventColor();
  _views = <String>[
    'Insert',
    'Query',
    'Update',
    'Delete',
  ];
  super.initState();
}

STEP 6: Using the FutureBuilder widget get the values from the database.  If the Snapshot.hasData contains data, then, you can load that database data to the Flutter calendar events.

appBar: AppBar(
    title: Text('SQL data'),
    leading: PopupMenuButton<String>(
      icon: Icon(Icons.calendar_today),
      itemBuilder: (BuildContext context) => _views.map((String choice) {
        return PopupMenuItem<String>(
          value: choice,
          child: Text(choice),
        );
      }).toList(),
      onSelected: (String value) {
        setState(() {
          if (value == 'Insert') {
            _insert();
          } else if (value == 'Query') {
            _query();
          } else if (value == 'Update') {
            _update();
          } else {
            _delete();
          }
        });
      },
    )),
body: FutureBuilder<List>(
    future: dbHelper.getAllRecords("flutter_calendar_events"),
    builder: (context, snapshot) {
      List<Appointment> collection = <Appointment>[];
  if (snapshot.data != null) {
    return ListView.builder(
      itemCount: 1,
      itemExtent: 550,
      itemBuilder: (context, int position) {
        var item = snapshot.data[position];
        Random random = new Random();
        for (int i = 0; i < snapshot.data.length; i++) {
          collection.add(
            Appointment(
              subject: item.row[1],
              startTime: _convertDateFromString(item.row[2]),
              endTime: _convertDateFromString(item.row[3]),
              color: _colorCollection[random.nextInt(9)],
            ),
          );
        }
        return SfCalendar(
          view: CalendarView.month,
          initialDisplayDate: DateTime(2021, 1, 4, 9, 0, 0),
          monthViewSettings: MonthViewSettings(showAgenda: true),
          dataSource: _getCalendarDataSource(collection),
        );
      },
    );
  } else {
    return CircularProgressIndicator();
  }
}));
void _initializeEventColor() {
  // ignore: deprecated_member_use
  _colorCollection = List<Color>();
  _colorCollection.add(const Color(0xFF0F8644));
  _colorCollection.add(const Color(0xFF8B1FA9));
  _colorCollection.add(const Color(0xFFD20100));
  _colorCollection.add(const Color(0xFFFC571D));
  _colorCollection.add(const Color(0xFF36B37B));
  _colorCollection.add(const Color(0xFF01A1EF));
  _colorCollection.add(const Color(0xFF3D4FB5));
  _colorCollection.add(const Color(0xFFE47C73));
  _colorCollection.add(const Color(0xFF636363));
  _colorCollection.add(const Color(0xFF0A8043));
}

View sample in GitHub

Flutter Calendar SQL data

 

Conclusion

I hope you enjoyed learning about how to load data from offline SQLite database to Flutter Calendar.

You can refer to our  Flutter Calender feature tour page to know about its other groundbreaking feature representations. You can also explore our Flutter Calendar documentation to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!



Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied