How to pass constructor arguments to the provider?

Viewed 715

I have the following class:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';

class Hisab with ChangeNotifier {
  Map<String, dynamic> _items = {};

  Hisab({
    @required String hisabDate,
    @required double total,
    @required bool paidStatus,
    @required String timestamp,
    @required Timestamp serverTimestamp,
  }) {
    _items['hisabDate'] = hisabDate;
    _items['total'] = total;
    _items['paidStatus'] = paidStatus;
    _items['timestamp'] = timestamp;
    _items['serverTimestamp'] = serverTimestamp;
  }

  Map<String, dynamic> get items => _items;
}

I created this class to hold items from firestore so that I can allow the user to filter and search by date.

When I try to initialize this class inside MultiProvider, I will have to pass arguments to the constructor.

return MultiProvider(
  providers: [
    ChangeNotifierProvider<CurrentIndex>(create: (_) => CurrentIndex()),
    ChangeNotifierProvider<Cart>(
      create: (_) => Cart(),
    ),
    ChangeNotifierProvider<Hisab>(
      create: (_) => Hisab(),  // Error: The parameter hisabDate is required
    ),
  ], 

Naturally, I get an error that I need to pass parameters. But of course, I haven't got the items from the firestore yet. I think that the way to handle this is by

  1. creating an empty constructor.
  2. Use that empty constructor in MultiProvider.
  3. Change the current constructor to fromMap constructor.
  4. Use the map constructor in the FutureBuilder that consumes the firestore items.
  5. [Maybe] add notifyListeners() in the constructor.

Is my thinking correct? If not, how to rectify it?

Thank you in advance.

0 Answers
Related