Flutter firestore tutorial | Game Points Example

 

Flutter Firestore :

Flutter firestore is a cloud based database for storing data using NoSQL database, even a beginner can easy maintain a database using firebase firestore.

Why flutter firestore because we need not handle server side coding, maintain hardware required and most important aspect is this operations are performed on cloud based can be accessed anywhere.

Database stores crucial information required to be processed in the app, database may be of local or global depending upon requirements.

We can store the data in terms of collections further categorized under documents, in this tutorial on flutter firestore we will store a game points in between two users using firebase firestore as backend database.

Flutter supports multi-platform app development and flutter firestore is a reliable and affordable database for beginner so we are using them together to make a sample app.

 

Flutter Firestore Video Tutorial :

Go through the below tutorial for more detailed information on firestore implementation in flutter.

 

Project Structure :

This image illustrates the implementation of a Flutter Firebase project.

flutter firestore

 

pubspec.yaml :

Add cloud_firestore plugin to pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  cloud_firestore: ^latest_version

 

 

Create a project in firebase

 

Then create a app in both android & iOS platforms

 

 

Now download

1) google-services.json

2) GoogleService-Info.plist

files after creating the projects and add them to flutter project

flutter firestore

 

Add classpath build.gradle [project]

classpath 'com.google.gms:google-services:4.3.3'

 

 

Apply plugin build.gradle [app]

apply plugin: 'com.google.gms.google-services'

 

 

main.dart :

Initialize with void main()

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

 

 

Add create a default class extending StatelessWidget

import 'package:flutter/material.dart';
import 'home.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Game Points',
      home: MyHomePage(),
    );
  }
}

 

 

game.dart :

Initialize a model class GameTable to fetch the values and update we are considering 3 variables here

final String name; 
final int score; 
final DocumentReference reference;

 

 

Map the data using respective key values

import 'package:cloud_firestore/cloud_firestore.dart';

class GameTable {
  final String name;
  final int score;
  final DocumentReference reference;

  GameTable.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['Name'] != null),
        assert(map['Score'] != null),
        name = map['Name'],
        score = map['Score'];

  GameTable.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data() as Map<String, dynamic>,
            reference: snapshot.reference);

  @override
  String toString() => "Record<$name:$score>";
}

 

 

Design a card view

Card(
  child: GridTile(
    child: InkWell(
      child: Container(
        padding: const EdgeInsets.all(8),
        color: Colors.black,
      ),
    ),
  ),
),

 

 

Now add the TextFields to display name and score

Column(
  children: <Widget>[
    Text(
      record.name,
      style: TextStyle(
        fontSize: 30,
        color: Colors.white,
        fontWeight: FontWeight.bold,
      ),
    ),
    SizedBox(height: 20),
    Text(
      record.score.toString(),
      style: TextStyle(
        fontSize: 30,
        color: Colors.white,
        fontWeight: FontWeight.bold,
      ),
    ),
  ],
),

 

 

Add a onTap() to update scores by 1 on every tap

onTap: () => record.reference.updateData({'Score': FieldValue.increment(1)}),

 

 

Use StreamBuilder to fetch data from firestore

StreamBuilder<QuerySnapshot>( );

 

 

Specify the collection name

stream: Firestore.instance.collection('androidcoding.in').snapshots(),

 

 

On Success fetch data return the data

_buildList(context, snapshot.data.documents);

 

 

Populate a list from the data

Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
  return ListView(
    padding: const EdgeInsets.only(top: 20.0),
    children: snapshot.map((data) => _buildListItem(context, data)).toList(),
  );
}

 

 

Display the list

Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
  final record = GameTable.fromSnapshot(data);

  return Padding(
    key: ValueKey(record.name),
    padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
    child: Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey),
        borderRadius: BorderRadius.circular(5.0),
      ),
      child: Card(
        child: GridTile(
          child: InkWell(
            onTap: () => _incrementScore(record.reference),
            child: Container(
              padding: const EdgeInsets.all(8),
              color: Colors.black,
              child: Column(
                children: <Widget>[
                  Text(
                    record.name,
                    style: TextStyle(
                      fontSize: 30,
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 20),
                  Text(
                    record.score.toString(),
                    style: TextStyle(
                      fontSize: 30,
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    ),
  );
}

void _incrementScore(DocumentReference reference) {
  reference.update({'Score': FieldValue.increment(1)});
}

 

 

Full Code :

Here’s a full code implementation for a Flutter app using Firestore:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firestore/game.dart';
import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Game Points')),
      body: _buildBody(context),
    );
  }

  Widget _buildBody(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('androidcoding.in').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return LinearProgressIndicator();
        return _buildList(context, snapshot.data.documents);
      },
    );
  }

  Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
    return ListView(
      padding: const EdgeInsets.only(top: 20.0),
      children: snapshot.map((data) => _buildListItem(context, data)).toList(),
    );
  }

  Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
    final record = GameTable.fromSnapshot(data);
    return Padding(
      key: ValueKey(record.name),
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.circular(5.0),
        ),
        child: Card(
          child: GridTile(
            child: InkWell(
              child: Container(
                padding: const EdgeInsets.all(8),
                child: Column(
                  children: <Widget>[
                    Text(
                      record.name,
                      style: TextStyle(
                        fontSize: 30,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 20),
                    Text(
                      record.score.toString(),
                      style: TextStyle(
                        fontSize: 30,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
                color: Colors.black,
              ),
              onTap: () => record.reference.updateData({'Score': FieldValue.increment(1)}),
            ),
          ),
        ),
      ),
    );
  }
}

 

 

Flutter firestore output :

This screen depicts the firestore tutorial showing game points

flutter firestore

If you have any questions, feel free to drop them in the comments below. If you enjoyed this tutorial, show us some love by liking and sharing for more exciting updates

Show Buttons
Hide Buttons
Read previous post:
Flutter routes, named routes | Navigator Routes

  Flutter Routes : Flutter Routes, navigator widget is used to move from one screen to another, the navigator manages...

Close