Sonotme
Sonotme

Reputation: 47

How to get a value from List<Map<String, dynamic>> in Flutter

I'm new to flutter and I have set of List<Map<String, dynamic>> data which contains the values name, amount and date.

e.g.

[{name: Product 1, amount: 24.5, date: 2019-07-07 22:21:57}]

[{name: Product 2, amount: 29.5, date: 2019-07-07 22:21:57}]

I'm passing the list into a list view builder, however before passing the list i need to validate the date in the list with the current date. Please find my code below:

import 'package:flutter/material.dart';
import 'package:learning_app/product.dart';

class BuildProduct extends StatelessWidget {
  final List<Map<String, dynamic>> products;
  final Function updateProduct;

  Tasks(this.products, this.updateProduct);

  Widget _buildCard() {
    DateTime _currentDate = DateTime.now();

    Widget ProductCard = Center(
      child: Text('No Products added'),
    );
    if (products.length > 0) {
      ProductCard = ListView.builder(
        scrollDirection: Axis.vertical,
        shrinkWrap: true,
        itemCount: products.length,
        itemBuilder: (BuildContext context, int index) {
          if(Need to compare the date in the products == currentDate) {
            return ProductCard(products[index], index, updateProduct);
          }
        }
      );
    }
    return ProductCard;
  }

  @override
  Widget build(BuildContext context) {
    return _buildCard();
  }
}

I need to read the date value in the list and compare that with the current date before each listview item is created. Any help is appreciated thanks

Upvotes: 3

Views: 26829

Answers (2)

JideGuru
JideGuru

Reputation: 7660

You can get your date with products[index]['date'] and then compare the date with the current date by using any of the following:

To check if the current date is after the product's date use: DateTime.now().isAfter(productDate)

OR

To check if the current date is before the product's date use: DateTime.now().isBefore(productDate).

Example:

DateTime productDate = DateTime.parse(products[index]['date']);
print(DateTime.now().isAfter(productDate));
print(DateTime.now().isBefore(productDate));

Good luck!

Upvotes: 2

Aaron Saunders
Aaron Saunders

Reputation: 33345

The map has a string as key, which in this case is date

products[index]['date']

Upvotes: 3

Related Questions