Tuesday, June 18, 2024
Google search engine
HomeToolsIntegrate Google Sheet to Flutter App

Integrate Google Sheet to Flutter App

Fetch data from google sheet to Flutter app

Google Sheet is a web-based spreadsheet application created by Google. Google Sheet allows collaborative editing in real-time. All users can see all the changes made by other users. Slidebar chat feature that allows a collaborative discussion. Google Sheets also support offline editing. It also supports multiple file formats and file types eg. .xlsx, .xls, .xlt, etc. Google Sheets can also be integrated with other Google products.

In this blog, we shall discuss how to integrate Google Sheets with the Flutter applications. Google Sheets provides us Script Editor to create an API. We can further use it to get the data from the Google Sheet to the Flutter app.

Work Flow of the module:

  • We will first make the doGet script in the google script editor.
  • We will add some data in the google sheets as a demo.
  • Then we will deploy the google script to get the API link.
  • We will then create a model class in our flutter project
  • Define its properties and the fromMap method to Map the JSON data with the model object.
  • Next, we will make the functions to decode the JSON data and fetch or map the JSON data with the List of model objects.
  • We will create a list of widgets that uses the model objects data.
  • To display the list of widgets we will need the Future Builder whose future will be the fetch data method that we have created in the 6 th step and its builder will return the list of widgets that we have created in the previous step.
***Demo***

Follow the following steps to open the Script Editor:

  • >Open Google Sheet
  • >Create a new sheet
  • >Click on the Tool button
  • >Select Script Editor

Now we have to write a doGet function to fetch the data from the Google sheets:

***Script***

To get the data we have to open the spreadsheet. To open it script editor provides three methods to open it using id, URL, open. We will use openById. We can get the id of the spreadsheet from the link https://docs.google.com/spreadsheets/d/id/edit#gid=0 . Now we will get all the values of the spreadSheet. Use for loop to iterate all the values and push them in a data list. Then using ContentService we can create the output in JSON format as shown above.

Deploy it as a web-app:

For deployment crate on the deploy button and click on New Deployment . Select the Web App from the Select Type. Select Anyone in Who can access and provide the Google account access.

After successfully deploying it we will get the URL.

Click on New Deployment

Choose Web App as Select Type

Provide access to AnyOne

Copy the URL to use it to get the data in JSON format

Package Used:

http | Dart Package
A composable, Future-based library for making HTTP requests. This package contains a set of high-level functions and…pub.dev

pubspec.yaml:

dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
http: ^0.12.2

Make a Model class to get the JSON data:

class MonumentModel {
String imageUrl;
String name;
String about;

MonumentModel({
this.about,
this.name,
this.imageUrl,
});

factory MonumentModel.fromMap(Map<String, dynamic> json) {
return MonumentModel(
about: json['about'],
name: json['name'],
imageUrl: json['imageUrl'],
);
}
}

fromMap method is used to Map the list of JSON items with the MonumentModel and return list. and fromJson is used to return the MonumentModel object with the JSON data.

Decoding Data:

This method takes

a responseBody. It returns a list of MonumentModel. All the data items in the JSON format are decoded and then the parsed data is then mapped with the MonumentModel using fromMap method and a list of MonumentModel is returned.

List<MonumentModel> decodeMonument(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed
.map<MonumentModel>((json) => MonumentModel.fromMap(json))
.toList();
}

Fetching JSON Data:

HTTP package provides us get method to fetch the JSON data. We will store the data in the response and the pass its body in the decode method to decode it.

Future<List<MonumentModel>> fetchMonument() async {
final response = await http.get(
'https://script.google.com/macros/s/AKfycbx9kO8lRb2UTMesbih4M4-EwlFxW7Zt58IMmHtFNGrG6bMF-eLlUCwvHuo9GdaAhPy-/exec');
if (response.statusCode == 200) {
return decodeMonument(response.body);
} else {
throw Exception('Unable to fetch data from the REST API');
}

Displaying the Data:

MyHomePage is a widget that takes a Future<List<MonumentModel>> . FutureBuilder is used as the data we got from the API is of Future type. Its Builder takes returns a CircularProgressIndicator if it does not has data else it returns a monumentList . monumentList is a list of all the monuments that we have got. It takes the data of the snapshot.

class MyHomePage extends StatelessWidget {
final Future<List<MonumentModel>> monuments;

MyHomePage({Key key, this.monuments}) : super(key: key);

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<List<MonumentModel>>(
future: monuments,
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? monumentList(snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
));
}
}

Now we will define monumentList Widget:

This is the actual UI that we see on our app. It has a simple Card with elevation 5 and a container with a Column. It has a name as a title, image, and description.

Widget monumentList( List<MonumentModel> monumentList) {
return ListView.builder(
itemCount: monumentList.length,
itemBuilder: (context, index) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"|| " + monumentList[index].name,
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 25),
),
Container(
child: Image.network(monumentList[index].imageUrl),
),
Container(
child: Text(
'\n' + monumentList[index].about,
style: TextStyle(
color: Colors.grey,
),
),
),
],
),
));
});
}

Conclusion:

In the article, I have explained how you can integrate google sheet with your flutter app. You can modify the script and code according to your requirement. This was a small introduction on how you create an API using google script and use that API to get the data stored in the sheets and use it in our app. You can also use some different approaches to display the data, please give it a try using initState method without using the FutureBuilder. You can get the data in a new list from the fetch function and directly use the ListView.builder and use the list data items to display the data. So please give it a try.

GitHub Link:

flutter-devs/flutter_google_sheet_example
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


🌸🌼🌸 Thank you for reading. 🌸🌼🌸


Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app 987tr project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments