mercredi 1 juillet 2020

Flutter web application: can't write to Firebase

I am trying to convert the boilerplate Flutter example into a web application and store the time of each click in Firestore. The program can login and the counter got incremented at each click. But it can't write to Firestore (checked via Firebase Console). Grateful if anyone can point out where I have done wrong, or pointer to the right approach. This is the code:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  void _incrementCounter()  {
    setState(() async {

      Firestore.instance.collection("click").add(
          {
            "time" : DateTime.now(),
          });
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title:  Text('DEMO')
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class AuthService {
  //Handle Authentication

  handleAuth() {
    FirebaseAuth.instance
        .signInWithEmailAndPassword(
        email: 'xxxxxxxx@gmail.com', password: 'xxxxxxxx');
    return StreamBuilder(
      stream: FirebaseAuth.instance.onAuthStateChanged,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => MyHomePage()),
          );
          ;
        } else {
          return Text('Login failed');
        }
      },
    );
  }
}



Aucun commentaire:

Enregistrer un commentaire