ravenousHydra
ravenousHydra

Reputation: 53

How to display items from Firestore by recently added in Flutter?

There's a problem which I'm trying to solve, it is displaying data by recently added to Firestore, through Flutter. What can be done in my case?

In React I would achieve this with useState hook, how can this be achieved in Flutter? I read about .sort(); method, is that a right way of doing this?

Code:

Form.dart

class FormText extends StatelessWidget {
  final String _labelText = 'Enter your weight..';
  final String _buttonText = 'Save';

  final _controller = TextEditingController();

  final dateFormat = new DateFormat.yMMMMd().add_jm();

  final _collection =
      FirebaseFirestore.instance.collection('weightMeasurement');

  void saveItemToList() {
    final weight = _controller.text;

    if (weight.isNotEmpty) {
      _collection.add({
        'weight': weight,
        'time': dateFormat.format(DateTime.now()),
      });
    } else {
      return null;
    }

    _controller.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Expanded(
          child: TextField(
            keyboardType: TextInputType.number,
            controller: _controller,
            decoration: InputDecoration(
              labelText: _labelText,
            ),
          ),
        ),
        FlatButton(
          color: Colors.blue,
          onPressed: saveItemToList,
          child: Text(
            _buttonText,
            style: TextStyle(
              color: Colors.white,
            ),
          ),
        ),
      ],
    );
  }
}

Measurements.dart

class RecentMeasurement {
  Widget buildList(QuerySnapshot snapshot) {
    return ListView.builder(
      reverse: false,
      itemCount: snapshot.docs.length,
      itemBuilder: (context, index) {
        final doc = snapshot.docs[index];
        return Dismissible(
          background: Container(color: Colors.red),
          key: Key(doc.id),
          onDismissed: (direction) {
            FirebaseFirestore.instance
                .collection('weightMeasurement')
                .doc(doc.id)
                .delete();
          },
          child: ListTile(
            title: Expanded(
              child: Card(
                margin: EdgeInsets.all(30.0),
                child: Column(
                  children: <Widget>[
                    Text('Current Weight: ' + doc['weight'] + 'kg'),
                    Text('Time added: ' + doc['time'].toString()),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

Layout.dart

class Layout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(30.0),
      child: Column(
        children: <Widget>[
          FormText(),
          StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance
                  .collection('weightMeasurement')
                  .snapshots(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) return LinearProgressIndicator();
                return Expanded(
                  child: RecentMeasurement().buildList(snapshot.data),
                );
              }),
        ],
      ),
    );
  }
}

Upvotes: 0

Views: 350

Answers (2)

Nedim Karavdic
Nedim Karavdic

Reputation: 252

You have to use "orderBy" on your collection, but previously You have to store something called timestamp. Make sure when You upload Your items to Firebase to also upload DateTime.now() along with Your items so You can order them by time. Do not forget to use Ascending direction since it will show you Your items ordered correctly.

Upvotes: 0

Madhan
Madhan

Reputation: 323

You can try order by . Here is an example

firestoreDb.collection("weightMeasurement")
            .orderBy("date", Query.Direction.ASCENDING)

Upvotes: 1

Related Questions