Skip to content

Commit c306a7a

Browse files
Merge pull request #1 from Tamilarasan-Paranthaman/master
FLUT-6648 - How to load data from firestore to Flutter DataTable (SfDataGrid).
2 parents c0e2395 + 83c8435 commit c306a7a

File tree

125 files changed

+4545
-1
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

125 files changed

+4545
-1
lines changed

.gitignore

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Miscellaneous
2+
*.class
3+
*.log
4+
*.pyc
5+
*.swp
6+
.DS_Store
7+
.atom/
8+
.buildlog/
9+
.history
10+
.svn/
11+
migrate_working_dir/
12+
13+
# IntelliJ related
14+
*.iml
15+
*.ipr
16+
*.iws
17+
.idea/
18+
19+
# The .vscode folder contains launch configuration and tasks you configure in
20+
# VS Code which you may wish to be included in version control, so this line
21+
# is commented out by default.
22+
#.vscode/
23+
24+
# Flutter/Dart/Pub related
25+
**/doc/api/
26+
**/ios/Flutter/.last_build_id
27+
.dart_tool/
28+
.flutter-plugins
29+
.flutter-plugins-dependencies
30+
.packages
31+
.pub-cache/
32+
.pub/
33+
/build/
34+
35+
# Web related
36+
lib/generated_plugin_registrant.dart
37+
38+
# Symbolication related
39+
app.*.symbols
40+
41+
# Obfuscation related
42+
app.*.map.json
43+
44+
# Android Studio will place build artifacts here
45+
/android/app/debug
46+
/android/app/profile
47+
/android/app/release

README.md

Lines changed: 172 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,172 @@
1-
# How-to-load-data-from-firestore-to-Flutter-DataTable-SfDataGrid-
1+
# How-to-load-data-from-firestore-to-Flutter-DataTable-SfDataGrid-
2+
3+
Load data from the [Firestore](https://firebase.google.com/docs/firestore) to the [Flutter DataGrid](https://www.syncfusion.com/flutter-widgets/flutter-datagrid) widget by fetching the data with the required collection name from Firestore. Then, create the rows for the DataGrid from document data.
4+
5+
The following steps explain how to load the data from the Firestore database for Flutter DataGrid:
6+
7+
## STEP 1:
8+
To get started with Firestore, refer to this [link](https://firebase.google.com/docs/firestore) and create the database in Firestore. In this KB, we have explained using the Firestore data as an example. We will not provide Firebase access files and a key.
9+
10+
## STEP 2:
11+
To fetch the data from the Firestore, you need to add the following package in the dependencies of pubspec.yaml.
12+
13+
```dart
14+
dependencies:
15+
flutter:
16+
sdk: flutter
17+
firebase_core: ^1.20.1
18+
cloud_firestore: ^3.4.4
19+
20+
```
21+
22+
## STEP 3:
23+
Import the following library into the flutter application:
24+
25+
```dart
26+
import 'package:flutter/material.dart';
27+
import 'package:cloud_firestore/cloud_firestore.dart';
28+
import 'package:firebase_core/firebase_core.dart';
29+
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
30+
```
31+
## STEP 4:
32+
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. In the following sample, we have shown how to perform CRUD operations from the Firestore. If you add the new document to the collection or update/delete the existing document in that collection, we have done the respective operations in the DataGrid based on the DocumentChangeType(added/ removed/ modified) in the document.
33+
34+
```dart
35+
class SfDataGridDemo extends StatefulWidget {
36+
const SfDataGridDemo({Key? key}) : super(key: key);
37+
38+
@override
39+
SfDataGridDemoState createState() => SfDataGridDemoState();
40+
}
41+
42+
class SfDataGridDemoState extends State<SfDataGridDemo> {
43+
late EmployeeDataSource employeeDataSource;
44+
List<Employee> employeeData = [];
45+
46+
final getData = FirebaseFirestore.instance.collection('Employee').snapshots();
47+
48+
Widget _buildDataGrid() {
49+
return StreamBuilder(
50+
stream: getData,
51+
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
52+
if (snapshot.hasData) {
53+
if (employeeData.isNotEmpty) {
54+
55+
// to update the value changed at runtime
56+
getDataGridRowFromDataBase(DocumentChange<Object?> data) {
57+
return DataGridRow(cells: [
58+
DataGridCell<String>(columnName: 'id', value: data.doc['id']),
59+
DataGridCell<String>(
60+
columnName: 'name', value: data.doc['name']),
61+
DataGridCell<String>(
62+
columnName: 'designation', value: data.doc['designation']),
63+
DataGridCell<String>(
64+
columnName: 'salary', value: data.doc['salary'].toString()),
65+
]);
66+
}
67+
68+
for (var data in snapshot.data!.docChanges) {
69+
if (data.type == DocumentChangeType.modified) {
70+
if (data.oldIndex == data.newIndex) {
71+
employeeDataSource.dataGridRows[data.oldIndex] =
72+
getDataGridRowFromDataBase(data);
73+
}
74+
employeeDataSource.updateDataGridSource();
75+
} else if (data.type == DocumentChangeType.added) {
76+
employeeDataSource.dataGridRows
77+
.add(getDataGridRowFromDataBase(data));
78+
employeeDataSource.updateDataGridSource();
79+
} else if (data.type == DocumentChangeType.removed) {
80+
employeeDataSource.dataGridRows.removeAt(data.oldIndex);
81+
employeeDataSource.updateDataGridSource();
82+
}
83+
}
84+
} else {
85+
for (var data in snapshot.data!.docs) {
86+
employeeData.add(Employee(
87+
id: data['id'],
88+
name: data['name'],
89+
designation: data['designation'],
90+
salary: data['salary'].toString()));
91+
}
92+
employeeDataSource = EmployeeDataSource(employeeData);
93+
}
94+
95+
return SfDataGrid(
96+
source: employeeDataSource,
97+
columns: getColumns,
98+
columnWidthMode: ColumnWidthMode.fill,
99+
);
100+
} else {
101+
return const Center(
102+
child: CircularProgressIndicator(),
103+
);
104+
}
105+
},
106+
);
107+
}
108+
@override
109+
void initState() {
110+
super.initState();
111+
}
112+
113+
@override
114+
Widget build(BuildContext context) {
115+
return Scaffold(
116+
appBar: AppBar(
117+
title: const Text('Syncfusion Flutter Datagrid FireStore Demo'),
118+
),
119+
body: _buildDataGrid(),
120+
);
121+
}
122+
}
123+
124+
```
125+
126+
## STEP 5:
127+
Create a data source class that extends with the [DataGridSource](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/DataGridSource-class.html) for mapping data to the [SfDataGrid](https://pub.dev/documentation/syncfusion_flutter_datagrid/latest/datagrid/SfDataGrid-class.html).
128+
129+
```dart
130+
class EmployeeDataSource extends DataGridSource {
131+
EmployeeDataSource(this.employeeData) {
132+
_buildDataRow();
133+
}
134+
135+
List<DataGridRow> dataGridRows = [];
136+
List<Employee> employeeData;
137+
138+
void _buildDataRow() {
139+
dataGridRows = employeeData
140+
.map<DataGridRow>((e) => DataGridRow(cells: [
141+
DataGridCell<String>(columnName: 'id', value: e.id),
142+
DataGridCell<String>(columnName: 'name', value: e.name),
143+
DataGridCell<String>(
144+
columnName: 'designation', value: e.designation),
145+
DataGridCell<String>(columnName: 'salary', value: e.salary),
146+
]))
147+
.toList();
148+
}
149+
150+
@override
151+
List<DataGridRow> get rows => dataGridRows;
152+
153+
@override
154+
DataGridRowAdapter buildRow(
155+
DataGridRow row,
156+
) {
157+
return DataGridRowAdapter(
158+
cells: row.getCells().map<Widget>((e) {
159+
return Container(
160+
alignment: Alignment.center,
161+
padding: const EdgeInsets.all(8.0),
162+
child: Text(e.value.toString()),
163+
);
164+
}).toList());
165+
}
166+
167+
void updateDataGridSource() {
168+
notifyListeners();
169+
}
170+
}
171+
172+
```

android/.gitignore

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
gradle-wrapper.jar
2+
/.gradle
3+
/captures/
4+
/gradlew
5+
/gradlew.bat
6+
/local.properties
7+
GeneratedPluginRegistrant.java
8+
9+
# Remember to never publicly share your keystore.
10+
# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app
11+
key.properties
12+
**/*.keystore
13+
**/*.jks

android/app/build.gradle

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
def localProperties = new Properties()
2+
def localPropertiesFile = rootProject.file('local.properties')
3+
if (localPropertiesFile.exists()) {
4+
localPropertiesFile.withReader('UTF-8') { reader ->
5+
localProperties.load(reader)
6+
}
7+
}
8+
9+
def flutterRoot = localProperties.getProperty('flutter.sdk')
10+
if (flutterRoot == null) {
11+
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
12+
}
13+
14+
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
15+
if (flutterVersionCode == null) {
16+
flutterVersionCode = '1'
17+
}
18+
19+
def flutterVersionName = localProperties.getProperty('flutter.versionName')
20+
if (flutterVersionName == null) {
21+
flutterVersionName = '1.0'
22+
}
23+
24+
apply plugin: 'com.android.application'
25+
apply plugin: 'kotlin-android'
26+
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
27+
apply plugin: 'com.google.gms.google-services'
28+
29+
30+
android {
31+
compileSdkVersion flutter.compileSdkVersion
32+
ndkVersion flutter.ndkVersion
33+
34+
compileOptions {
35+
sourceCompatibility JavaVersion.VERSION_1_8
36+
targetCompatibility JavaVersion.VERSION_1_8
37+
}
38+
39+
kotlinOptions {
40+
jvmTarget = '1.8'
41+
}
42+
43+
sourceSets {
44+
main.java.srcDirs += 'src/main/kotlin'
45+
}
46+
47+
defaultConfig {
48+
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
49+
applicationId "com.example.flutter_application"
50+
// You can update the following values to match your application needs.
51+
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
52+
minSdkVersion flutter.minSdkVersion
53+
targetSdkVersion flutter.targetSdkVersion
54+
versionCode flutterVersionCode.toInteger()
55+
versionName flutterVersionName
56+
}
57+
58+
buildTypes {
59+
debug {
60+
minifyEnabled false
61+
}
62+
release {
63+
// TODO: Add your own signing config for the release build.
64+
// Signing with the debug keys for now, so `flutter run --release` works.
65+
signingConfig signingConfigs.debug
66+
}
67+
}
68+
}
69+
70+
flutter {
71+
source '../..'
72+
}
73+
74+
dependencies {
75+
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
76+
implementation platform('com.google.firebase:firebase-bom:30.1.0')
77+
}

android/app/google-services.json

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
{
2+
"project_info": {
3+
"project_number": "485159817284",
4+
"project_id": "employeedatagrid",
5+
"storage_bucket": "employeedatagrid.appspot.com"
6+
},
7+
"client": [
8+
{
9+
"client_info": {
10+
"mobilesdk_app_id": "1:485159817284:android:864a525dc882fbb1f52c11",
11+
"android_client_info": {
12+
"package_name": "com.example.flutter_application"
13+
}
14+
},
15+
"oauth_client": [
16+
{
17+
"client_id": "485159817284-g82jbdd8lfbse2j0roi0pbhd4j87jod0.apps.googleusercontent.com",
18+
"client_type": 3
19+
}
20+
],
21+
"api_key": [
22+
{
23+
"current_key": "AIzaSyDYsDkQIHmuMNO4wqrhIP5RC75w6sVrrfo"
24+
}
25+
],
26+
"services": {
27+
"appinvite_service": {
28+
"other_platform_oauth_client": [
29+
{
30+
"client_id": "485159817284-g82jbdd8lfbse2j0roi0pbhd4j87jod0.apps.googleusercontent.com",
31+
"client_type": 3
32+
}
33+
]
34+
}
35+
}
36+
}
37+
],
38+
"configuration_version": "1"
39+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
2+
package="com.example.flutter_application">
3+
<!-- The INTERNET permission is required for development. Specifically,
4+
the Flutter tool needs it to communicate with the running application
5+
to allow setting breakpoints, to provide hot reload, etc.
6+
-->
7+
<uses-permission android:name="android.permission.INTERNET"/>
8+
</manifest>

0 commit comments

Comments
 (0)