Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/

# IntelliJ related
*.iml
*.ipr
*.iws
.idea/

# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/

# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
/build/

# Symbolication related
app.*.symbols

# Obfuscation related
app.*.map.json

# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
175 changes: 173 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,173 @@
# how-to-implement-asynchronous-sorting-of-data-retrieved-from-firestore-in-a-flutter-data-table
How to implement asynchronous sorting of data retrieved from Firestore in a Flutter DataTable (SfDataGrid)?
# How to implement asynchronous sorting of data retrieved from Firestore in a Flutter DataTable (SfDataGrid)?

In this article, we will discuss how to implement asynchronous sorting in a [Flutter DataGrid](https://www.syncfusion.com/flutter-widgets/flutter-datagrid) that retrieves data from Firestore. We will cover the steps and techniques required to fetch data from Firestore, handle asynchronous operations, and dynamically sort the data based on user interactions.

## STEP 1:
You need to add the following package in the dependencies of pubspec.yaml.

```dart
firebase_core: ^2.13.0
cloud_firestore: ^4.7.1

```

## STEP 2:
Import the following library into the flutter application:

```dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';

```

## STEP 3:
Initialize the [SfDataGrid](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid-class.html) with all the required details. Fetch the data from the Firestore database by passing the required collection name. The [StreamController](https://api.flutter.dev/flutter/dart-async/StreamController-class.html) that will be used to control the loading state. It will emit true or false values to show or hide the loading indicator.

```dart
const defaultFirebaseOptions = FirebaseOptions(
apiKey: '',
authDomain: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
);

StreamController<bool> loadingController = StreamController<bool>();

class SfDataGridDemo extends StatefulWidget {
const SfDataGridDemo({Key? key}) : super(key: key);
@override
SfDataGridDemoState createState() => SfDataGridDemoState();
}

class SfDataGridDemoState extends State<SfDataGridDemo> {
late EmployeeDataSource employeeDataSource;
List<Employee> employeeData = [];

@override
void initState() {
super.initState();
employeeDataSource = EmployeeDataSource([]);
}

final getDataFromFireStore =
FirebaseFirestore.instance.collection('Sync1').snapshots();
Widget _buildDataGrid() {
return StreamBuilder<QuerySnapshot>(
stream: getDataFromFireStore,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
for (var data in snapshot.data!.docs) {
employeeData.add(Employee(
id: data['id'],
name: data['name'],
designation: data['designation'],
salary: data['salary'].toString()));
}
employeeDataSource = EmployeeDataSource(employeeData);
return StreamBuilder<bool>(
stream: loadingController.stream,
builder: (context, snapshot) {
return Stack(children: [
SfDataGrid(
source: employeeDataSource,
columns: getColumns,
allowSorting: true,
columnWidthMode: ColumnWidthMode.fill,
gridLinesVisibility: GridLinesVisibility.both,
headerGridLinesVisibility: GridLinesVisibility.both,
),
if (snapshot.data == true)
const Center(
child: CircularProgressIndicator(),
),
]);
});
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Syncfusion Flutter Datagrid FireStore Demo'),
),
body: _buildDataGrid(),
);
}
}

```

## STEP 4:
The performSorting method accepts a list of DataGridRow objects as input. It includes a simulated asynchronous that applies the [Future.delay](https://api.flutter.dev/flutter/dart-async/Future/Future.delayed.html) for a specific time to imitate server-side processing. Upon completion of the delay, the loadingController is updated to signal the end of loading. If the current column's sortDirection is set to ascending, the dataGridRow variable is assigned a new list of DataGridRow objects. Each row represents an employee, with cells containing their respective attributes. The isSuspend variable is then set to false, indicating the completion of the sorting process. If the sortDirection is descending, the same steps are followed.

```dart
bool isSuspend = true;
@override
Future<void> performSorting(List<DataGridRow> rows) async {
if (!isSuspend || sortedColumns.isEmpty) {
return;
}
loadingController.add(true);
await Future<void>.delayed(const Duration(seconds: 2));
loadingController.add(false);

for (final column in sortedColumns) {
if (column.sortDirection == DataGridSortDirection.ascending) {
final snapshot = await FirebaseFirestore.instance
.collection('Sync1')
.orderBy(column.name)
.get();
fetchData(snapshot);
buildData(employeeData);
isSuspend = false;
notifyListeners();
} else if (column.sortDirection == DataGridSortDirection.descending) {
final snapshot = await FirebaseFirestore.instance
.collection('Sync1')
.orderBy(column.name,
descending:
column.sortDirection == DataGridSortDirection.descending)
.get();
fetchData(snapshot);
buildData(employeeData);
isSuspend = false;
notifyListeners();
}
}

isSuspend = true;
}

List<Employee> fetchData(QuerySnapshot<Map<String, dynamic>> snapshot) {
return employeeData = snapshot.docs
.map((data) => Employee(
id: data['id'],
name: data['name'],
designation: data['designation'],
salary: data['salary'].toString(),
))
.toList();
}

List<DataGridRow> buildData(List<Employee> employeeData) {
return dataGridRows = employeeData
.map<DataGridRow>((e) => DataGridRow(cells: [
DataGridCell<String>(columnName: 'id', value: e.id),
DataGridCell<String>(columnName: 'name', value: e.name),
DataGridCell<String>(
columnName: 'designation', value: e.designation),
DataGridCell<String>(columnName: 'salary', value: e.salary),
]))
.toList();
}

```
13 changes: 13 additions & 0 deletions android/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java

# Remember to never publicly share your keystore.
# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app
key.properties
**/*.keystore
**/*.jks
72 changes: 72 additions & 0 deletions android/app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
namespace "com.example.flutter_application_1"
compileSdkVersion flutter.compileSdkVersion
ndkVersion flutter.ndkVersion

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}

kotlinOptions {
jvmTarget = '1.8'
}

sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}

defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.flutter_application_1"
// You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
minSdkVersion flutter.minSdkVersion
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}

buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}

flutter {
source '../..'
}

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
7 changes: 7 additions & 0 deletions android/app/src/debug/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
33 changes: 33 additions & 0 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:label="flutter_application_1"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.example.flutter_application_1

import io.flutter.embedding.android.FlutterActivity

class MainActivity: FlutterActivity() {
}
12 changes: 12 additions & 0 deletions android/app/src/main/res/drawable-v21/launch_background.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="?android:colorBackground" />

<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
12 changes: 12 additions & 0 deletions android/app/src/main/res/drawable/launch_background.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />

<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
Binary file added android/app/src/main/res/mipmap-hdpi/ic_launcher.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added android/app/src/main/res/mipmap-mdpi/ic_launcher.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading