问:
App notification badge update using Firebase Messaging
I'm using flutter_app_badger and Firebase Messaging to set a notification system which would update number in app badger when a new notification is coming. I'm working in Flutterflow so my approach might be a bit awkward. So far I managed to do two things:

Create a separate function in the app which updates app badger while app is working;

Set the notification system that is triggered by the action in app;

But I can't combine the two. I have the following push_notification_handler code and trying how to put FlutterAppBadger.updateBadgeCount() function it.

```<code>import 'dart:async';
import 'dart:convert';
import 'serialization_util.dart';
import '../backend.dart';
import '../../flutter_flow/flutter_flow_theme.dart';
import '../../flutter_flow/flutter_flow_util.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import '../../index.dart';
import '../../main.dart';

final _handledMessageIds = <String?>{};

class PushNotificationsHandler extends StatefulWidget {
  const PushNotificationsHandler({Key? key, required this.child})
      : super(key: key);

  final Widget child;

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

class _PushNotificationsHandlerState extends State<PushNotificationsHandler> {
  bool _loading = false;

  Future handleOpenedPushNotification() async {
    if (isWeb) {
      return;
    }

    final notification = await FirebaseMessaging.instance.getInitialMessage();
    if (notification != null) {
      await _handlePushNotification(notification);
    }
    FirebaseMessaging.onMessageOpenedApp.listen(_handlePushNotification);
  }

  Future _handlePushNotification(RemoteMessage message) async {
    if (_handledMessageIds.contains(message.messageId)) {
      return;
    }
    _handledMessageIds.add(message.messageId);

    if (mounted) {
      setState(() => _loading = true);
    }
    try {
      final initialPageName = message.data['initialPageName'] as String;
      final initialParameterData = getInitialParameterData(message.data);
      final pageBuilder = pageBuilderMap[initialPageName];
      if (pageBuilder != null) {
        final page = await pageBuilder(initialParameterData);
        await Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => page),
        );
      }
    } catch (e) {
      print('Error: $e');
    } finally {
      if (mounted) {
        setState(() => _loading = false);
      }
    }
  }

  @override
  void initState() {
    super.initState();
    handleOpenedPushNotification();
  }

  @override
  Widget build(BuildContext context) => _loading
      ? Container(
          color: FlutterFlowTheme.of(context).primaryBtnText,
          child: Image.asset(
            'assets/images/Screen_Shot_2022-11-22_at_12.59.57.png',
            fit: BoxFit.contain,
          ),
        )
      : widget.child;
}

final pageBuilderMap = <String, Future<Widget> Function(Map<String, dynamic>)>{
  'SignInSignUpPage': (data) async => SignInSignUpPageWidget(),
  'ForgotPasswordPage': (data) async => ForgotPasswordPageWidget(),
  'ContactsListPage': (data) async => ContactsListPageWidget(
        tabToOpen: getParameter(data, 'tabToOpen'),
      ),
  'SyncProcessPage': (data) async => SyncProcessPageWidget(),
  'SyncConfirmationPage': (data) async => SyncConfirmationPageWidget(),
  'ContactDetailsPage': (data) async => ContactDetailsPageWidget(
        idReference: getParameter(data, 'idReference'),
        comment: getParameter(data, 'comment'),
      ),
  'ContactDeletePage': (data) async => ContactDeletePageWidget(
        idReference: getParameter(data, 'idReference'),
        comment: getParameter(data, 'comment'),
      ),
  'ContactInvitationPage': (data) async => ContactInvitationPageWidget(
        idReference: getParameter(data, 'idReference'),
      ),
  'AddConfirmationAfterInvitePage': (data) async =>
      AddConfirmationAfterInvitePageWidget(
        uID: getParameter(data, 'uID'),
        phraseState: getParameter(data, 'phraseState'),
      ),
  'AddContactsOptionPage': (data) async => AddContactsOptionPageWidget(),
  'SearchNewContactsPage': (data) async => SearchNewContactsPageWidget(),
  'NewContactInvitationConfirmationPage': (data) async =>
      NewContactInvitationConfirmationPageWidget(),
  'NewContactScanPage': (data) async => NewContactScanPageWidget(),
  'AddConfirmationAfterScanPageNew': (data) async =>
      AddConfirmationAfterScanPageNewWidget(
        uID: getParameter(data, 'uID'),
        phraseState: getParameter(data, 'phraseState'),
      ),
  'AddConfirmationAfterScanPageOld': (data) async =>
      AddConfirmationAfterScanPageOldWidget(
        uID: getParameter(data, 'uID'),
        phraseState: getParameter(data, 'phraseState'),
      ),
  'ShareProfileOptionsPage': (data) async => ShareProfileOptionsPageWidget(),
  'InAppQRcodeSharePage': (data) async => InAppQRcodeSharePageWidget(),
  'WebQRcodeSharePage': (data) async => WebQRcodeSharePageWidget(),
  'ProfileEditPage': (data) async => ProfileEditPageWidget(),
  'GameSettingsPage': (data) async => GameSettingsPageWidget(),
  'GamePage': (data) async => GamePageWidget(),
  'TutorialPage': (data) async => TutorialPageWidget(),
  'AboutPage': (data) async => AboutPageWidget(),
  'FAQPage': (data) async => FAQPageWidget(),
  'PrivacyPolicyPage': (data) async => PrivacyPolicyPageWidget(),
};

bool hasMatchingParameters(Map<String, dynamic> data, Set<String> params) =>
    params.any((param) => getParameter(data, param) != null);

Map<String, dynamic> getInitialParameterData(Map<String, dynamic> data) {
  try {
    final parameterDataStr = data['parameterData'];
    if (parameterDataStr == null ||
        parameterDataStr is! String ||
        parameterDataStr.isEmpty) {
      return {};
    }
    return jsonDecode(parameterDataStr) as Map<String, dynamic>;
  } catch (e) {
    print('Error parsing parameter data: $e');
    return {};
  }
}

</code>```

Would be super grateful for any advice!

Body:
I'm using flutter_app_badger and Firebase Messaging to set a notification system which would update number in app badger when a new notification is coming. I'm working in Flutterflow so my approach might be a bit awkward. So far I managed to do two things:

Create a separate function in the app which updates app badger while app is working;

Set the notification system that is triggered by the action in app;

But I can't combine the two. I have the following push_notification_handler code and trying how to put FlutterAppBadger.updateBadgeCount() function it.

import 'dart:async';
import 'dart:convert';
import 'serialization_util.dart';
import '../backend.dart';
import '../../flutter_flow/flutter_flow_theme.dart';
import '../../flutter_flow/flutter_flow_util.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import '../../index.dart';
import '../../main.dart';

final _handledMessageIds = <String?>{};

class PushNotificationsHandler extends StatefulWidget {
  const PushNotificationsHandler({Key? key, required this.child})
      : super(key: key);

  final Widget child;

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

class _PushNotificationsHandlerState extends State<PushNotificationsHandler> {
  bool _loading = false;

  Future handleOpenedPushNotification() async {
    if (isWeb) {
      return;
    }

    final notification = await FirebaseMessaging.instance.getInitialMessage();
    if (notification != null) {
      await _handlePushNotification(notification);
    }
    FirebaseMessaging.onMessageOpenedApp.listen(_handlePushNotification);
  }

  Future _handlePushNotification(RemoteMessage message) async {
    if (_handledMessageIds.contains(message.messageId)) {
      return;
    }
    _handledMessageIds.add(message.messageId);

    if (mounted) {
      setState(() => _loading = true);
    }
    try {
      final initialPageName = message.data['initialPageName'] as String;
      final initialParameterData = getInitialParameterData(message.data);
      final pageBuilder = pageBuilderMap[initialPageName];
      if (pageBuilder != null) {
        final page = await pageBuilder(initialParameterData);
        await Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => page),
        );
      }
    } catch (e) {
      print('Error: $e');
    } finally {
      if (mounted) {
        setState(() => _loading = false);
      }
    }
  }

  @override
  void initState() {
    super.initState();
    handleOpenedPushNotification();
  }

  @override
  Widget build(BuildContext context) => _loading
      ? Container(
          color: FlutterFlowTheme.of(context).primaryBtnText,
          child: Image.asset(
            'assets/images/Screen_Shot_2022-11-22_at_12.59.57.png',
            fit: BoxFit.contain,
          ),
        )
      : widget.child;
}

final pageBuilderMap = <String, Future<Widget> Function(Map<String, dynamic>)>{
  'SignInSignUpPage': (data) async => SignInSignUpPageWidget(),
  'ForgotPasswordPage': (data) async => ForgotPasswordPageWidget(),
  'ContactsListPage': (data) async => ContactsListPageWidget(
        tabToOpen: getParameter(data, 'tabToOpen'),
      ),
  'SyncProcessPage': (data) async => SyncProcessPageWidget(),
  'SyncConfirmationPage': (data) async => SyncConfirmationPageWidget(),
  'ContactDetailsPage': (data) async => ContactDetailsPageWidget(
        idReference: getParameter(data, 'idReference'),
        comment: getParameter(data, 'comment'),
      ),
  'ContactDeletePage': (data) async => ContactDeletePageWidget(
        idReference: getParameter(data, 'idReference'),
        comment: getParameter(data, 'comment'),
      ),
  'ContactInvitationPage': (data) async => ContactInvitationPageWidget(
        idReference: getParameter(data, 'idReference'),
      ),
  'AddConfirmationAfterInvitePage': (data) async =>
      AddConfirmationAfterInvitePageWidget(
        uID: getParameter(data, 'uID'),
        phraseState: getParameter(data, 'phraseState'),
      ),
  'AddContactsOptionPage': (data) async => AddContactsOptionPageWidget(),
  'SearchNewContactsPage': (data) async => SearchNewContactsPageWidget(),
  'NewContactInvitationConfirmationPage': (data) async =>
      NewContactInvitationConfirmationPageWidget(),
  'NewContactScanPage': (data) async => NewContactScanPageWidget(),
  'AddConfirmationAfterScanPageNew': (data) async =>
      AddConfirmationAfterScanPageNewWidget(
        uID: getParameter(data, 'uID'),
        phraseState: getParameter(data, 'phraseState'),
      ),
  'AddConfirmationAfterScanPageOld': (data) async =>
      AddConfirmationAfterScanPageOldWidget(
        uID: getParameter(data, 'uID'),
        phraseState: getParameter(data, 'phraseState'),
      ),
  'ShareProfileOptionsPage': (data) async => ShareProfileOptionsPageWidget(),
  'InAppQRcodeSharePage': (data) async => InAppQRcodeSharePageWidget(),
  'WebQRcodeSharePage': (data) async => WebQRcodeSharePageWidget(),
  'ProfileEditPage': (data) async => ProfileEditPageWidget(),
  'GameSettingsPage': (data) async => GameSettingsPageWidget(),
  'GamePage': (data) async => GamePageWidget(),
  'TutorialPage': (data) async => TutorialPageWidget(),
  'AboutPage': (data) async => AboutPageWidget(),
  'FAQPage': (data) async => FAQPageWidget(),
  'PrivacyPolicyPage': (data) async => PrivacyPolicyPageWidget(),
};

bool hasMatchingParameters(Map<String, dynamic> data, Set<String> params) =>
    params.any((param) => getParameter(data, param) != null);

Map<String, dynamic> getInitialParameterData(Map<String, dynamic> data) {
  try {
    final parameterDataStr = data['parameterData'];
    if (parameterDataStr == null ||
        parameterDataStr is! String ||
        parameterDataStr.isEmpty) {
      return {};
    }
    return jsonDecode(parameterDataStr) as Map<String, dynamic>;
  } catch (e) {
    print('Error parsing parameter data: $e');
    return {};
  }
}

Would be super grateful for any advice!


来源: stackexchange

问:
Dialogflow ES PHP Client Library 500 (Internal Server Error)
Dialogflow and PHP newbie here.

I have created and implemented a mini button-based chatbot using Dialogflow ES PHP client library in one of my client's WordPress site.

Everything worked as expected in my local environment, but when I pushed my codes to the staging site, I got a 500 (Internal Server Error) in my DevTool. The Dialogflow console still got my initial intent from staging and responded accordingly with logs without any error, however.

This is the error shown in my server error.log

```<code>PHP Fatal error:
Uncaught Google\ApiCore\ApiException: {
    "message": "Input text not set.",
    "code": 3,
    "status": "INVALID_ARGUMENT",
    "details": []
}
thrown in /var/www/my-staging-domain.com/public/vendor/google/gax/src/ApiException.php on line 267, referer: https://my-staging-domain.com/
</code>```

AJAX call frontend JS file

```<code>async function sendDataToDialogflow(text, sessionID) {
  let result;
  try {
    result = await $.ajax({
      url: /dialogflow.php,
      type: "POST",
      data: {
        query: text,
        lang: "en",
        sessionId: sessionID,
      },
      success: function(res, status, xhr) {
        setDialogflowResponse(res);
      },
      error: function(error) {
        console.warn(error);
      }
    });

    return result;

  } catch (error) {
    console.log(error);
  }
}
</code>```

My backend dialogflow.php file setting

```<code><?php

namespace Google\Cloud\Samples\Dialogflow;
namespace Google\Protobuf;
use Google\Cloud\Dialogflow\V2\SessionsClient;
use Google\Cloud\Dialogflow\V2\TextInput;
use Google\Cloud\Dialogflow\V2\QueryInput;
use Google\Cloud\Dialogflow\V2\Context;

require $_SERVER['DOCUMENT_ROOT']. '/vendor/autoload.php';

if (isset($_POST) && isset($_POST["query"])) {
    $query = $_POST["query"];
    $lang = $_POST["lang"];
    $sessionId = $_POST["sessionId"];

    if (isset($_POST['query'])) {
        detect_intent_texts($projectId,$query,$sessionId);
    }

}

function detect_intent_texts($projectId, $text, $sessionId, $context = '', $parameters = '',  $languageCode = 'en-US')
{
    // -------------- new session --------------
    $credential = array('credentials' => $_SERVER['DOCUMENT_ROOT'].'/client-secret.json');
    $sessionsClient = new SessionsClient($credential);
    $session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
    //printf('Session path: %s' . PHP_EOL, $session);

    // -------------- create text input --------------
    $textInput = new TextInput();
    $textInput->setText($text);
    $textInput->setLanguageCode($languageCode);

    if($context !== '') {
        // -------------- create context struct --------------
        $contextStruct = new Struct();
        $contextStruct->setFields($context['parameters']);

        // -------------- create context input --------------
        $contextInput = new Context();
        $contextInput->setLifespanCount($context['lifespan']);
        $contextInput->setName($context['name']);
        $contextInput->setParameters($contextStruct);
    }

    if($parameters !== '') {
        $paramStruct = new Struct();
        $paramStruct->setFields($parameters['parameters']);
    }

    // -------------- create query input --------------
    $queryInput = new QueryInput();
    $queryInput->setText($textInput);

    // -------------- get response and relevant info --------------
    $response = ($parameters ? $sessionsClient->detectIntent($session, $queryInput) : $sessionsClient->detectIntent($session, $queryInput));
    $responseId = $response->getResponseId();
    $queryResult = $response->getQueryResult();
    $fields = $queryResult->getParameters()->getFields();
    $jsonString = $queryResult->serializeToJsonString();
    $queryText = $queryResult->getQueryText();
    $intent = $queryResult->getIntent();
    $displayName = $intent->getDisplayName();
    $confidence = $queryResult->getIntentDetectionConfidence();
    $fulfillmentText = $queryResult->getFulfillmentText();
    $fulfillmentMessages = json_decode($queryResult->getFulfillmentMessages()[0]->serializeToJsonString(), true);

    function get_field_value($field)
    {
        $kind = $field->getKind();
        if ($kind == "string_value")
            return $field->getStringValue();
        else if ($kind == "number_value")
            return $field->getNumberValue();
        else if ($kind == "bool_value")
            return $field->getBoolValue();
        else if ($kind == "null_value")
            return $field->getNullValue();
        else if ($kind == "list_value") {
            $list_values = $field->getListValue()->getValues();
            $values = [];
            foreach($list_values as $list_value)
                $values[] = get_field_value($list_value);
            return $values;
        }
        else if ($kind == "struct_value")
            return $field->getStructValue();
    }

    $parameters = [];
    foreach($fields as $key => $field) {
        $parameters[$key] = get_field_value($field);
    }

    $returnResponse = array(
        'responseId' => $responseId,
        'fulfillmentText' => $fulfillmentText,
        'fulfillmentMessages' => $fulfillmentMessages,
        'queryText' => $queryText,
        'parameters' => json_decode($jsonString)->parameters
    );

    echo json_encode($returnResponse);

    $sessionsClient->close();
}
</code>```

composer.json

```<code>{
    "require": {
        "google/cloud-dialogflow": "^0.29.0",
        "google/protobuf": "^3.21",
        "protobuf-php/protobuf": "^0.1.3",
        "ext-bcmath": "*"
    }
}
</code>```

Any insights on this issue would be much appreciated!

I've updated staging from http to https, but this didn't fix the issue.

I've read through all the documents/questions on stackoverflow I could find, but in vain.

ContentLicense: CC BY-SA 4.0

Body:
Dialogflow and PHP newbie here.

I have created and implemented a mini button-based chatbot using Dialogflow ES PHP client library in one of my client's WordPress site.

Everything worked as expected in my local environment, but when I pushed my codes to the staging site, I got a 500 (Internal Server Error) in my DevTool. The Dialogflow console still got my initial intent from staging and responded accordingly with logs without any error, however.

This is the error shown in my server error.log

PHP Fatal error:
Uncaught Google\ApiCore\ApiException: {
    "message": "Input text not set.",
    "code": 3,
    "status": "INVALID_ARGUMENT",
    "details": []
}
thrown in /var/www/my-staging-domain.com/public/vendor/google/gax/src/ApiException.php on line 267, referer: https://my-staging-domain.com/

AJAX call frontend JS file

async function sendDataToDialogflow(text, sessionID) {
  let result;
  try {
    result = await $.ajax({
      url: /dialogflow.php,
      type: "POST",
      data: {
        query: text,
        lang: "en",
        sessionId: sessionID,
      },
      success: function(res, status, xhr) {
        setDialogflowResponse(res);
      },
      error: function(error) {
        console.warn(error);
      }
    });

    return result;

  } catch (error) {
    console.log(error);
  }
}

My backend dialogflow.php file setting

<?php

namespace Google\Cloud\Samples\Dialogflow;
namespace Google\Protobuf;
use Google\Cloud\Dialogflow\V2\SessionsClient;
use Google\Cloud\Dialogflow\V2\TextInput;
use Google\Cloud\Dialogflow\V2\QueryInput;
use Google\Cloud\Dialogflow\V2\Context;

require $_SERVER['DOCUMENT_ROOT']. '/vendor/autoload.php';

if (isset($_POST) && isset($_POST["query"])) {
    $query = $_POST["query"];
    $lang = $_POST["lang"];
    $sessionId = $_POST["sessionId"];

    if (isset($_POST['query'])) {
        detect_intent_texts($projectId,$query,$sessionId);
    }

}

function detect_intent_texts($projectId, $text, $sessionId, $context = '', $parameters = '',  $languageCode = 'en-US')
{
    // -------------- new session --------------
    $credential = array('credentials' => $_SERVER['DOCUMENT_ROOT'].'/client-secret.json');
    $sessionsClient = new SessionsClient($credential);
    $session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
    //printf('Session path: %s' . PHP_EOL, $session);

    // -------------- create text input --------------
    $textInput = new TextInput();
    $textInput->setText($text);
    $textInput->setLanguageCode($languageCode);

    if($context !== '') {
        // -------------- create context struct --------------
        $contextStruct = new Struct();
        $contextStruct->setFields($context['parameters']);

        // -------------- create context input --------------
        $contextInput = new Context();
        $contextInput->setLifespanCount($context['lifespan']);
        $contextInput->setName($context['name']);
        $contextInput->setParameters($contextStruct);
    }

    if($parameters !== '') {
        $paramStruct = new Struct();
        $paramStruct->setFields($parameters['parameters']);
    }

    // -------------- create query input --------------
    $queryInput = new QueryInput();
    $queryInput->setText($textInput);

    // -------------- get response and relevant info --------------
    $response = ($parameters ? $sessionsClient->detectIntent($session, $queryInput) : $sessionsClient->detectIntent($session, $queryInput));
    $responseId = $response->getResponseId();
    $queryResult = $response->getQueryResult();
    $fields = $queryResult->getParameters()->getFields();
    $jsonString = $queryResult->serializeToJsonString();
    $queryText = $queryResult->getQueryText();
    $intent = $queryResult->getIntent();
    $displayName = $intent->getDisplayName();
    $confidence = $queryResult->getIntentDetectionConfidence();
    $fulfillmentText = $queryResult->getFulfillmentText();
    $fulfillmentMessages = json_decode($queryResult->getFulfillmentMessages()[0]->serializeToJsonString(), true);

    function get_field_value($field)
    {
        $kind = $field->getKind();
        if ($kind == "string_value")
            return $field->getStringValue();
        else if ($kind == "number_value")
            return $field->getNumberValue();
        else if ($kind == "bool_value")
            return $field->getBoolValue();
        else if ($kind == "null_value")
            return $field->getNullValue();
        else if ($kind == "list_value") {
            $list_values = $field->getListValue()->getValues();
            $values = [];
            foreach($list_values as $list_value)
                $values[] = get_field_value($list_value);
            return $values;
        }
        else if ($kind == "struct_value")
            return $field->getStructValue();
    }

    $parameters = [];
    foreach($fields as $key => $field) {
        $parameters[$key] = get_field_value($field);
    }

    $returnResponse = array(
        'responseId' => $responseId,
        'fulfillmentText' => $fulfillmentText,
        'fulfillmentMessages' => $fulfillmentMessages,
        'queryText' => $queryText,
        'parameters' => json_decode($jsonString)->parameters
    );

    echo json_encode($returnResponse);

    $sessionsClient->close();
}

composer.json

{
    "require": {
        "google/cloud-dialogflow": "^0.29.0",
        "google/protobuf": "^3.21",
        "protobuf-php/protobuf": "^0.1.3",
        "ext-bcmath": "*"
    }
}

Any insights on this issue would be much appreciated!

I've updated staging from http to https, but this didn't fix the issue.

I've read through all the documents/questions on stackoverflow I could find, but in vain.


问:
Do we need to project gps data via UTM before conducting K means clustering?
I'm working with a dataset of GPS coordinates, and I'm wondering if I need to project the data from the WGS84 coordinate system to UTM before using the K-means clustering algorithm.

I feel like because K means requires we calculate distances between different points, simply calculating distance via L2 norm of latitude and longitude coordinates is going to be inaccurate.

Therefore, before we run our K means algorithm, we should apply a UTM projection so all the coordinates's L2 distances from each-other are reflective of their true distances.

In my case, all WGS84 coordinates are datapoints from a single city in Eastern Europe if that matters.


问:
Typescript '{ readonly id: number... is missing the following properties from type 'Product': _id
Typescript is throwing an error when attempting to return my custom class object for not matching the specified return type. The error is as follows:

TS2739: Type '{ readonly id: number; readonly productName: string; readonly price: number; readonly displayPrice: string; readonly images: string[]; toString: () => string; }' is missing the following properties from type 'Product': _id, _productName, _price, _images

I created a custom Product class with corresponding getters like below:

export default class Product {

    private readonly _id: number
    private readonly _productName: string
    private readonly _price: number
    private readonly _images: string[]

    constructor(id: number, productName: string, price: number,
                image0: string, image1?: string, image2?: string,
                image3?: string, image4?: string, image5?: string) {
        this._id = id
        this._productName = productName
        this._price = price
        this._images = [ image0, image1, image2, image3, image4, image5 ]
...
```
<p>And then I have a pinia function which iterates through a list of products and returns one:</p>
<pre class="lang-js prettyprint-override"><code>    state: () => {
        return {
            size: 0,
            products: [] as Product[]
        }
    },
    actions: {
        getProductById(id: Number): Product | null {
            for (const item of this.products) {
                if (id == item.id) {
                    return item   //Typescript error generated here
                }
            }
            return null
        },
</code>```

As far as I can tell, the type of "item" should clearly be type Product which matches the return type and has the associated properties -  "_id, _productName, _price, _images" - that Typescript is warning about not having.
However, it seems the return type "Product" of getProductById() isn't matching the type of the values inside the products array.

Does anyone know why this might be happening? Even based on the typescript error, it seems like all values are present.

Body:
Typescript is throwing an error when attempting to return my custom class object for not matching the specified return type. The error is as follows:

TS2739: Type '{ readonly id: number; readonly productName: string; readonly price: number; readonly displayPrice: string; readonly images: string[]; toString: () => string; }' is missing the following properties from type 'Product': _id, _productName, _price, _images

I created a custom Product class with corresponding getters like below:

export default class Product {

    private readonly _id: number
    private readonly _productName: string
    private readonly _price: number
    private readonly _images: string[]

    constructor(id: number, productName: string, price: number,
                image0: string, image1?: string, image2?: string,
                image3?: string, image4?: string, image5?: string) {
        this._id = id
        this._productName = productName
        this._price = price
        this._images = [ image0, image1, image2, image3, image4, image5 ]
...

And then I have a pinia function which iterates through a list of products and returns one:

    state: () => {
        return {
            size: 0,
            products: [] as Product[]
        }
    },
    actions: {
        getProductById(id: Number): Product | null {
            for (const item of this.products) {
                if (id == item.id) {
                    return item   //Typescript error generated here
                }
            }
            return null
        },

As far as I can tell, the type of "item" should clearly be type Product which matches the return type and has the associated properties -  "_id, _productName, _price, _images" - that Typescript is warning about not having.
However, it seems the return type "Product" of getProductById() isn't matching the type of the values inside the products array.

Does anyone know why this might be happening? Even based on the typescript error, it seems like all values are present.


问:
How to separate cookies according to tenants when they have the same server
We have a site with dynamic prefix according to tenants: *.chat.ourdomain.com.

This site makes requests to a nodejs server manager.ourdomain.com.
We need to save some data in cookies, but it should be separated for each tenant.
e.g. - aaa.chat.ourdomain.com should send only its cookies to server manager.ourdomain.com, and bbb.chat.ourdomain.com need to send its data on cookies.

We have this code in server:

```<code>res.cookie(cookieKey, cookieVal, {
            secure: req.headers.origin.indexOf('https') > -1,
            httpOnly: true,
            maxAge: 30 * 24 * 60 * 60 * 1000
});
</code>```

The domain is the default: manager.ourdomain.com, so each request to the common server, the browser sends both site's cookies (aaa.chat.ourdomain.com and bbb.chat.ourdomain.com).

How can we fix that?
What I found is only to use the 'path' attribute, and add the tenant as parameter to all server requests:

app.use("/manager/:tenant", routes)

and upon cookie creation:

```<code>const tenant = getTenantFromOrigin(req.headers.origin); // aaa or bbb or another tenant...
res.cookie(cookieKey, cookieVal, {
            secure: req.headers.origin.indexOf('https') > -1,
            httpOnly: true,
            maxAge: 30 * 24 * 60 * 60 * 1000,
            path: '/manager/${tenant}'
});
</code>```

Is it a normal approach, or maybe someone has another idea?

Body:
We have a site with dynamic prefix according to tenants: *.chat.ourdomain.com.

This site makes requests to a nodejs server manager.ourdomain.com.
We need to save some data in cookies, but it should be separated for each tenant.
e.g. - aaa.chat.ourdomain.com should send only its cookies to server manager.ourdomain.com, and bbb.chat.ourdomain.com need to send its data on cookies.

We have this code in server:

res.cookie(cookieKey, cookieVal, {
            secure: req.headers.origin.indexOf('https') > -1,
            httpOnly: true,
            maxAge: 30 * 24 * 60 * 60 * 1000
});

The domain is the default: manager.ourdomain.com, so each request to the common server, the browser sends both site's cookies (aaa.chat.ourdomain.com and bbb.chat.ourdomain.com).

How can we fix that?
What I found is only to use the 'path' attribute, and add the tenant as parameter to all server requests:

app.use("/manager/:tenant", routes)

and upon cookie creation:

const tenant = getTenantFromOrigin(req.headers.origin); // aaa or bbb or another tenant...
res.cookie(cookieKey, cookieVal, {
            secure: req.headers.origin.indexOf('https') > -1,
            httpOnly: true,
            maxAge: 30 * 24 * 60 * 60 * 1000,
            path: '/manager/${tenant}'
});

Is it a normal approach, or maybe someone has another idea?


问:
How to download weighted average ensemble model ? with a file format h5 or tf.lite
I am building an average weighted ensemble model, everything is going ok with the code. But, I could not download the model since there is no name for it. How can I assign a name for the model? The code is as below

```<code>models = [ EfficientNetB0_model, EfficientNetB1_model, DenseNet121_model, DenseNet169_model, DenseNet201_model
            ,EfficientNetB2_model, EfficientNetB3_model, EfficientNetB4_model, EfficientNetB5_model, EfficientNetB6_model,
          EfficientNetB7_model, EfficientNetV2B0_model, EfficientNetV2B1_model, EfficientNetV2B2_model, EfficientNetV2B3_model,
          EfficientNetV2L_model, EfficientNetV2M_model, EfficientNetV2S_model, InceptionResNetV2_model, InceptionV3_model,
             ResNet50_model, ResNet50V2_model, ResNet101_model, ResNet101V2_model, ResNet152_model,
          ResNet152V2_model, VGG16_model, VGG19_model, Xception_model, MobileNet_model , MobileNetV2_model
        ]

preds = [model.predict(X_test) for model in models]
preds=np.array(preds)
weights = [0.2, 0.3, 0.0, 0.1, 0.0,
           0.3, 0.2, 0.1, 0.0, 0.3,
           0.1, 0.3, 0.3, 0.1, 0.0,
           0.1, 0.2, 0.1, 0.1, 0.1,
           0.4, 0.0, 0.2, 0.1, 0.4,
           0.0, 0.0, 0.1, 0.1, 0.0, 0.0
           ]

#Use tensordot to sum the products of all elements over specified axes.
weighted_preds = np.tensordot(preds, weights, axes=((0),(0)))
weighted_ensemble_prediction = np.argmax(weighted_preds, axis=1)

weighted_accuracy = accuracy_score(y_test, weighted_ensemble_prediction)

print('Accuracy Score for model1 = ', accuracy1)
print('Accuracy Score for model2 = ', accuracy2)
print('Accuracy Score for model3 = ', accuracy3)
print('Accuracy Score for model4 = ', accuracy4)
print('Accuracy Score for model5 = ', accuracy5)
print('Accuracy Score for model6 = ', accuracy6)
print('Accuracy Score for model7 = ', accuracy7)
print('Accuracy Score for model8 = ', accuracy8)
print('Accuracy Score for model9 = ', accuracy9)
print('Accuracy Score for model10 = ', accuracy10)
print('Accuracy Score for model11 = ', accuracy11)
print('Accuracy Score for model12 = ', accuracy12)
print('Accuracy Score for model13 = ', accuracy13)
print('Accuracy Score for model14 = ', accuracy14)
print('Accuracy Score for model15 = ', accuracy15)
print('Accuracy Score for model16 = ', accuracy16)
print('Accuracy Score for model17 = ', accuracy17)
print('Accuracy Score for model18 = ', accuracy18)
print('Accuracy Score for model19 = ', accuracy19)
print('Accuracy Score for model20 = ', accuracy20)
print('Accuracy Score for model21 = ', accuracy21)
print('Accuracy Score for model22 = ', accuracy22)
print('Accuracy Score for model23 = ', accuracy23)
print('Accuracy Score for model24 = ', accuracy24)
print('Accuracy Score for model25 = ', accuracy25)
print('Accuracy Score for model26 = ', accuracy26)
print('Accuracy Score for model27 = ', accuracy27)
print('Accuracy Score for model28 = ', accuracy28)
print('Accuracy Score for model29 = ', accuracy29)
print('Accuracy Score for model30 = ', accuracy30)
print('Accuracy Score for model31 = ', accuracy31)

print('Accuracy Score for average ensemble = ', ensemble_accuracy)
print('Accuracy Score for weighted average ensemble = ', weighted_accuracy)
</code>```

I have tried to search for a solution, but I could not find can you help me with that? and I am expecting to get a solution of how to download the weighted average ensemble model. Thank you!

Body:
I am building an average weighted ensemble model, everything is going ok with the code. But, I could not download the model since there is no name for it. How can I assign a name for the model? The code is as below

models = [ EfficientNetB0_model, EfficientNetB1_model, DenseNet121_model, DenseNet169_model, DenseNet201_model
            ,EfficientNetB2_model, EfficientNetB3_model, EfficientNetB4_model, EfficientNetB5_model, EfficientNetB6_model,
          EfficientNetB7_model, EfficientNetV2B0_model, EfficientNetV2B1_model, EfficientNetV2B2_model, EfficientNetV2B3_model,
          EfficientNetV2L_model, EfficientNetV2M_model, EfficientNetV2S_model, InceptionResNetV2_model, InceptionV3_model,
             ResNet50_model, ResNet50V2_model, ResNet101_model, ResNet101V2_model, ResNet152_model,
          ResNet152V2_model, VGG16_model, VGG19_model, Xception_model, MobileNet_model , MobileNetV2_model
        ]

preds = [model.predict(X_test) for model in models]
preds=np.array(preds)
weights = [0.2, 0.3, 0.0, 0.1, 0.0,
           0.3, 0.2, 0.1, 0.0, 0.3,
           0.1, 0.3, 0.3, 0.1, 0.0,
           0.1, 0.2, 0.1, 0.1, 0.1,
           0.4, 0.0, 0.2, 0.1, 0.4,
           0.0, 0.0, 0.1, 0.1, 0.0, 0.0
           ]

#Use tensordot to sum the products of all elements over specified axes.
weighted_preds = np.tensordot(preds, weights, axes=((0),(0)))
weighted_ensemble_prediction = np.argmax(weighted_preds, axis=1)

weighted_accuracy = accuracy_score(y_test, weighted_ensemble_prediction)

print('Accuracy Score for model1 = ', accuracy1)
print('Accuracy Score for model2 = ', accuracy2)
print('Accuracy Score for model3 = ', accuracy3)
print('Accuracy Score for model4 = ', accuracy4)
print('Accuracy Score for model5 = ', accuracy5)
print('Accuracy Score for model6 = ', accuracy6)
print('Accuracy Score for model7 = ', accuracy7)
print('Accuracy Score for model8 = ', accuracy8)
print('Accuracy Score for model9 = ', accuracy9)
print('Accuracy Score for model10 = ', accuracy10)
print('Accuracy Score for model11 = ', accuracy11)
print('Accuracy Score for model12 = ', accuracy12)
print('Accuracy Score for model13 = ', accuracy13)
print('Accuracy Score for model14 = ', accuracy14)
print('Accuracy Score for model15 = ', accuracy15)
print('Accuracy Score for model16 = ', accuracy16)
print('Accuracy Score for model17 = ', accuracy17)
print('Accuracy Score for model18 = ', accuracy18)
print('Accuracy Score for model19 = ', accuracy19)
print('Accuracy Score for model20 = ', accuracy20)
print('Accuracy Score for model21 = ', accuracy21)
print('Accuracy Score for model22 = ', accuracy22)
print('Accuracy Score for model23 = ', accuracy23)
print('Accuracy Score for model24 = ', accuracy24)
print('Accuracy Score for model25 = ', accuracy25)
print('Accuracy Score for model26 = ', accuracy26)
print('Accuracy Score for model27 = ', accuracy27)
print('Accuracy Score for model28 = ', accuracy28)
print('Accuracy Score for model29 = ', accuracy29)
print('Accuracy Score for model30 = ', accuracy30)
print('Accuracy Score for model31 = ', accuracy31)

print('Accuracy Score for average ensemble = ', ensemble_accuracy)
print('Accuracy Score for weighted average ensemble = ', weighted_accuracy)

I have tried to search for a solution, but I could not find can you help me with that? and I am expecting to get a solution of how to download the weighted average ensemble model. Thank you!


问:
Login with Firebase giving " Error (auth/missing-email) " on Android Device for an EXPO React Native App
I'm developing an Instagram like React Native App with Redux as State manager, but whenever I try to login using some android device, it gives me error :

```<code>Firebase: Error (auth/missing-email).
</code>```

But when I try to login using the web, it works fine !!!
Here's the code snippet for login:

```<code>const userLoginHandler =() =>{
    signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
              const user = userCredential.user;
              console.log("User Logged in");
              dispatch(userLoginRedux(user));
            })
            .catch((error) => {
              const errorMessage = error.message;
              console.log(errorMessage);
            });
  }
</code>```

This is how I trigger the login:

```<code><Button
        title="Login" type="clear" size="md"
        buttonStyle={styles.btnStyle}
        containerStyle={styles.btnContainer}
        titleStyle={styles.btnTitleStyle}
        onPress={ userLoginHandler }
      />
</code>```

The email and password are states which are handled on change of the Input fields.

Any fix for this issue? Appreciate any help ;)

I tried to login without the Redux part, but the problem still persists.
The weird thing being it works absolutely fine for the Expo Web.

Body:
I'm developing an Instagram like React Native App with Redux as State manager, but whenever I try to login using some android device, it gives me error :

Firebase: Error (auth/missing-email).

But when I try to login using the web, it works fine !!!
Here's the code snippet for login:

const userLoginHandler =() =>{
    signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
              const user = userCredential.user;
              console.log("User Logged in");
              dispatch(userLoginRedux(user));
            })
            .catch((error) => {
              const errorMessage = error.message;
              console.log(errorMessage);
            });
  }

This is how I trigger the login:

<Button
        title="Login" type="clear" size="md"
        buttonStyle={styles.btnStyle}
        containerStyle={styles.btnContainer}
        titleStyle={styles.btnTitleStyle}
        onPress={ userLoginHandler }
      />

The email and password are states which are handled on change of the Input fields.

Any fix for this issue? Appreciate any help ;)

I tried to login without the Redux part, but the problem still persists.
The weird thing being it works absolutely fine for the Expo Web.


问:
How to clear matplotlib RectangleSelector with command?
I have RectangleSelector append on multiple axes as below code.

```<code>selectors = []
for idx, ax in enumerate(axes):
    selectors.append(RectangleSelector(
    axes[idx], select_callback,
    useblit=True,
    button=[1, 3],
    minspanx=5, minspany=5,
    spancoords='pixels',
    interactive=True))
</code>```

In other partial code, once I call axes[i].figure.canvas.draw_idle() while selection exist on graph then my app getting freeze. So I would like to clear all selection before call axes[i].figure.canvas.draw_idle(). Any advice or guidance on this would be greatly appreciated, Thanks.

Body:
I have RectangleSelector append on multiple axes as below code.

selectors = []
for idx, ax in enumerate(axes):
    selectors.append(RectangleSelector(
    axes[idx], select_callback,
    useblit=True,
    button=[1, 3],
    minspanx=5, minspany=5,
    spancoords='pixels',
    interactive=True))

In other partial code, once I call axes[i].figure.canvas.draw_idle() while selection exist on graph then my app getting freeze. So I would like to clear all selection before call axes[i].figure.canvas.draw_idle(). Any advice or guidance on this would be greatly appreciated, Thanks.


问:
how to call header image while converting site html to WordPress?
I am converting an HTML website to a WordPress site and don't know how to call the header image in the header. Also, I want a unique header image on each category page. Is there a way to do it without a plugin?Background image below header</p>
```<code><div class="ftcat-header">
        <div class="ftcat-header-image-wrap">
            <div class="ftcat-header-image-overlay"></div>
                                <div class="ftcat-header-image skip-lazy" style='background-image: url("<?php echo wp_get_upload_dir()['baseurl'] . '/2022/02/cuisine.jpg'; ?>");'></div>
                            <div class="ftcat-header-content">
                <h1 class="ftcat-header-title">
                    Cuisine - Revues Des Produits et Guides d'Achat                    </h1>
                <div class="ftcat-header-search">
                    <form role="search" method="get" class="search-form" action="https://ideadear.com/">
                        <input type="search" class="search-field" placeholder="Search for the best product..." value="" name="s" />
                        <button type="submit" class="search-submit">Search</button>
                    </form>
                </div>
                <div class="ftcat-header-meta">
                                                                </div>
            </div>
        </div>
                </div>
</code>```

Body:
I am converting an HTML website to a WordPress site and don't know how to call the header image in the header. Also, I want a unique header image on each category page. Is there a way to do it without a plugin?Background image below header

                                <div class="ftcat-header-image skip-lazy" style='background-image: url("<?php echo wp_get_upload_dir()['baseurl'] . '/2022/02/cuisine.jpg'; ?>");'>

                    Cuisine - Revues Des Produits et Guides d'Achat

                    <form role="search" method="get" class="search-form" action="https://ideadear.com/">
                        <input type="search" class="search-field" placeholder="Search for the best product..." value="" name="s" />
                        <button type="submit" class="search-submit">Search</button>
                    </form>


问:
Get the length of the text in an input in pixels
Simply, I'm trying to get the length of the text in the input in pixels (not the caret position).

I thought about creating a dummy input and putting the exact same value into it and measuring its width, but even if there is no width specified an input element is always constant width, and using a different element from an input could make the results inaccurate because of the existing styles.


问:
Move assignment operator not invoked
Can somebody explain this code:</p>
```<code>void Move(Person& lhs, Person&& rhs)
{
    lhs = rhs; //invokes copy assignment instead of move assignment
    //lhs = (Person&&) rhs; //casting to && invokes move assignment.
}
</code>```

Title: Move assignment operator not invoked

Body:
Can somebody explain this code:

void Move(Person& lhs, Person&& rhs)
{
    lhs = rhs; //invokes copy assignment instead of move assignment
    //lhs = (Person&&) rhs; //casting to && invokes move assignment.
}


问:
Flutter prop drilling problem here, I'm trying to return cart item count widget build on my home screen for each specific item
I have successfully built a home screen that can navigate to cart page and show items in cart but I now struggle to display that same item count in the home screen for each items. The methods I'm using are not suitable and competable for this task  please see the controllers included and the images attached. Idealy I want to display from home page the quantity for each specific item that has been added to cart.

```<code>// Laundry Categories as list on the home screen
GetBuilder<LaundrySpecialtyController>(
  builder: (laundrySpecialties) {
    var _specialty = laundrySpecialties.laundrySpecialtyList;
    return laundrySpecialties.isLoaded
        ? SizedBox(
            height: Dimensions.screenWidth / 3,
            width: Dimensions.screenWidth / 1.10,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount:
                  laundrySpecialties.laundrySpecialtyList.length,
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: () {
                    Get.toNamed(RouteHelper.getLaundrySpecialties(
                        index, 'home'));
                  },
                  child: Container(
                    //color: Colors.red,
                    margin: EdgeInsets.symmetric(
                        horizontal: Dimensions.screenWidth / 100),
                    width: Dimensions.screenWidth / 3.4,
                    height: Dimensions.screenHeight / 2.8,
                    child: Column(
                      children: [
                        Stack(
                          children: [
                            Container(
                              width: Dimensions.screenWidth / 3.8,
                              height: Dimensions.screenHeight / 8,
                              // margin: EdgeInsets.only(
                              //     bottom: Dimensions.height10),
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  fit: BoxFit.cover,
                                  image: AssetImage(laundrySpecialties
                                      .laundrySpecialtyList[index]
                                      .img!),
                                ),
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(
                                        Dimensions.radius15),
                                    topRight: Radius.circular(
                                        Dimensions.radius15)),
                                //color: Colors.white54,
                                // gradient: const LinearGradient(
                                //   begin: Alignment.topRight,
                                //   end: Alignment.bottomLeft,
                                //   colors: [
                                //     Colors.white,
                                //     Colors.white,
                                //   ],
                                // ),
                              ),
                            ),
                            GetBuilder<
                                    RecommendedSpecialtyController>(
                                builder: (controller) {
                              return (Container(
                                child: Positioned(
                                  right: 1,
                                  top: 1,
                                  child: GetBuilder<CartController>(
                                      builder: (cartController) {
                                    var _cartList =
                                        cartController.getItems;
                                    if (cartController.totalItems >=
                                        1) {
                                      return Container(
                                        width: 25,
                                        height: 25,
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          boxShadow: const [
                                            BoxShadow(
                                              color:
                                                  Color(0xffB09B71),
                                              blurRadius: 2.0,
                                              offset: Offset(1, 1),
                                            ),
                                          ],
                                          borderRadius:
                                              BorderRadius.circular(
                                                  Dimensions
                                                          .height10 *
                                                      5),
                                          border: Border.all(
                                            width: 1,
                                            color: const Color(
                                                0xffB09B71),
                                          ),
                                        ),
                                        child: Center(
                                          child: SmallText(
                                            size: Dimensions.font16,
                                            text: _cartList[index]
                                                .quantity
                                                .toString(),
                                            fontWeight:
                                                FontWeight.w400,
                                            color: const Color(
                                                0xff966C3B),
                                          ),
                                        ),
                                        // AppIcon(
                                        //   size: Dimensions.iconSize26 + 2,
                                        //   iconSize: Dimensions.iconSize24,
                                        //   backgroundColor: Colors.white,
                                        //   iconColor: const Color(0xffB09B71),
                                        //   icon: Icons.add,
                                        // ),
                                      );
                                    } else {
                                      return Container();
                                    }
                                  }),
                                ),
                              ));
                            }
                                // GetBuilder<
                                //         RecommendedSpecialtyController>(
                                //     builder: (controller) {
                                //   return Container(
                                //     child: controller.totalItems >= 1
                                //         ? Positioned(
                                //             right: 1,
                                //             top: 1,
                                //             child: Container(
                                //               width: 25,
                                //               height: 25,
                                //               decoration: BoxDecoration(
                                //                 color: Colors.white,
                                //                 boxShadow: const [
                                //                   BoxShadow(
                                //                     color:
                                //                         Color(0xffB09B71),
                                //                     blurRadius: 2.0,
                                //                     offset: Offset(1, 1),
                                //                   ),
                                //                 ],
                                //                 borderRadius: BorderRadius
                                //                     .circular(Dimensions
                                //                             .height10 *
                                //                         5),
                                //                 border: Border.all(
                                //                   width: 1,
                                //                   color: const Color(
                                //                       0xffB09B71),
                                //                 ),
                                //               ),
                                //               child: Center(
                                //                 child: SmallText(
                                //                   size: Dimensions.font16,
                                //                   text: '4',
                                //                   fontWeight:
                                //                       FontWeight.w400,
                                //                   color: const Color(
                                //                       0xff966C3B),
                                //                 ),
                                //               ),
                                //               // AppIcon(
                                //               //   size: Dimensions.iconSize26 + 2,
                                //               //   iconSize: Dimensions.iconSize24,
                                //               //   backgroundColor: Colors.white,
                                //               //   iconColor: const Color(0xffB09B71),
                                //               //   icon: Icons.add,
                                //               // ),
                                //             ),
                                //           )
                                //         : Container(),
                                //   );
                                // }),
                                // Positioned(
                                //   right: 0,
                                //   left: 0,
                                //   bottom: 0,
                                //   child: Container(
                                //     width: Dimensions.screenWidth / 4,
                                //     decoration:
                                //         BoxDecoration(color: Colors.white),
                                //     child: Center(
                                //       child: SmallText(
                                //         text:
                                //             'R ${laundrySpecialties.laundrySpecialtyList[index].price!.toString()}.00',
                                //         fontWeight: FontWeight.w600,
                                //         color: const Color(0xffCFC5A5),
                                //       ),
                                //     ),
                                //   ),
                                // )
                                ),
                          ],
                        ),
                        Container(
                          width: Dimensions.screenWidth / 3.8,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.only(
                                  bottomLeft: Radius.circular(
                                      Dimensions.radius15),
                                  bottomRight: Radius.circular(
                                      Dimensions.radius15)),
                              // gradient: const LinearGradient(
                              //   begin: Alignment.bottomRight,
                              //   end: Alignment.topLeft,
                              //   colors: [
                              //     Color(0xff966C3B),
                              //     Color(0xffCFC5A5),
                              //   ],
                              // ),
                              color: Colors.white),
                          child: Center(
                            child: SmallText(
                              text: laundrySpecialties
                                  .laundrySpecialtyList[index].name!,
                              fontWeight: FontWeight.w600,
                              color: Colors.black54,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          )
        : Transform.scale(
            scale: 0.5,
            child: CircularProgressIndicator(
              color: AppColors.mainColor,
            ),
          );
  },
),
</code>```

**Bellow is the laundry controller for the model
**

```<code>import 'package:get/get.dart';
import 'package:izinto/helpers/data/repository/laundry_specialty_repo.dart';

import '../models/cart_model.dart';
import '../models/popular_specialty_model.dart';
import 'cart_controller.dart';
import '../helpers/data/repository/cart_repo.dart';

class LaundrySpecialtyController extends GetxController {
  final LaundrySpecialtyRepo laundrySpecialtyRepo;
  final CartRepo cartRepo;
  LaundrySpecialtyController({required this.cartRepo,required this.laundrySpecialtyRepo});

  Map<int, CartModel> _items = {};

  List<dynamic> _laundrySpecialtyList = [];
  List<dynamic> get laundrySpecialtyList => _laundrySpecialtyList;
  late CartController _cart;

  bool _isLoaded = false;
  bool get isLoaded => _isLoaded;

  int _quantity = 0;
  int get quantity => _quantity;
  int _inCartItems = 0;
  int get inCartItems => _inCartItems + _quantity;

  get getItems => _items;

  Future<void> getLaundrySpecialtyList() async {
    Response response = await laundrySpecialtyRepo.getLaundrySpecialtyList();
    if (response.statusCode == 200) {
      print('got laundry specialties');
      // print(response.body);
      _laundrySpecialtyList = [];
      _laundrySpecialtyList
          .addAll(Specialty.fromJson(response.body).specialties);
      print(_laundrySpecialtyList);
      _isLoaded = true;
      update();
    } else {
      print('laundry not working ${response.statusCode}');
    }
  }

  void addItem(SpecialtyModel specialty, int quantity) {
    var totalQuantity = 0;
    if (_items.containsKey(specialty.id!)) {
      _items.update(specialty.id!, (value) {
        totalQuantity = value.quantity! + quantity;

        return CartModel(
          id: value.id,
          name: value.name,
          price: value.price,
          time: DateTime.now().toString(),
          img: value.img,
          type: value.type,
          material: value.material,
          quantity: value.quantity! + quantity,
          isExist: true,
          provider: value.provider,
          specialty: specialty,
        );
      });

      if (totalQuantity <= 0) {
        _items.remove(specialty.id);
      }
    } else {
      if (quantity > 0) {
        _items.putIfAbsent(specialty.id!, () {
          return CartModel(
            id: specialty.id,
            name: specialty.name,
            price: specialty.price,
            time: DateTime.now().toString(),
            img: specialty.img,
            type: specialty.type,
            material: specialty.material,
            quantity: quantity,
            isExist: true,
            provider: specialty.provider,
            specialty: specialty,
          );
        });
      } else {
        Get.snackbar(
          'Item count 0', 'Please select items to add to cart',
          // backgroundColor: AppColors.mainColor, colorText: Colors.white
        );
      }
    }
    cartRepo.addToCartList(getItems);
    update();
  }

  void setQuantity(bool isIncrement) {
    if (isIncrement) {
      _quantity = checkQuantity(_quantity + 1);
      // print('number of items ' + _quantity.toString());
    } else {
      _quantity = checkQuantity(_quantity - 1);
      // print('items reduced to ' + _quantity.toString());
    }
    update();
  }

  int checkQuantity(int quantity) {
    if ((_inCartItems + quantity) < 0) {
      Get.snackbar(
        'Item count 0', 'You don\'t have items',
        // backgroundColor: AppColors.mainColor, colorText: Colors.white
      );
      if (_inCartItems > 0) {
        _quantity = -_inCartItems;
        return _quantity;
      }
      return 0;
    } else if ((_inCartItems + quantity) > 20) {
      Get.snackbar('Item count 20', 'Maximum number of items selected');
      return 20;
    } else {
      return quantity;
    }
  }
}

</code>```

The cart repo

```<code>import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../models/cart_model.dart';
import '../../../utils/app_constants.dart';

class CartRepo {
  final SharedPreferences sharedPreferences;
  CartRepo({required this.sharedPreferences});

  List<String> cart = [];
  List<String> cartHistory = [];

  void addToCartList(List<CartModel> cartList) {
    sharedPreferences.remove(AppConstants.CART_LIST);
    sharedPreferences.remove(AppConstants.CART_HISTORY_LIST);
    var time = DateTime.now().toString();
    cart = [];
    /*
      convert objects to string because shared preferences only accepts string
     */

    cartList.forEach((element) {
      element.time = time;
      return cart.add(jsonEncode(element));
    });

    sharedPreferences.setStringList(AppConstants.CART_LIST, cart);
    // print(sharedPreferences.getStringList(AppConstants.CART_LIST));
    // getCartList();
  }

  List<CartModel> getCartList() {
    List<String> carts = [];
    if (sharedPreferences.containsKey(AppConstants.CART_LIST)) {
      carts = sharedPreferences.getStringList(AppConstants.CART_LIST)!;
      // print('inside getCartList ' + carts.toString());
    }
    List<CartModel> cartList = [];

    carts.forEach(
        (element) => cartList.add(CartModel.fromJson(jsonDecode(element))));

    return cartList;
  }

  List<CartModel> getCartHistoryList() {
    if (sharedPreferences.containsKey(AppConstants.CART_HISTORY_LIST)) {
      // cartHistory = [];
      cartHistory =
          sharedPreferences.getStringList(AppConstants.CART_HISTORY_LIST)!;
    }

    List<CartModel> cartListHistory = [];
    cartHistory.forEach((element) =>
        cartListHistory.add(CartModel.fromJson(jsonDecode(element))));
    return cartListHistory;
  }

  void addToCartHistoryList() {
    if (sharedPreferences.containsKey(AppConstants.CART_HISTORY_LIST)) {
      cartHistory =
          sharedPreferences.getStringList(AppConstants.CART_HISTORY_LIST)!;
    }
    for (int i = 0; i < cart.length; i++) {
      print('history list ' + cart[i]);
      cartHistory.add(cart[i]);
    }
    removeCart();
    sharedPreferences.setStringList(
        AppConstants.CART_HISTORY_LIST, cartHistory);
    print('The length of history list is ' +
        getCartHistoryList().length.toString());
    for (int j = 0; j < getCartHistoryList().length; j++) {
      print('The time for the order is ' +
          getCartHistoryList()[j].time.toString());
    }
  }

  void removeCart() {
    cart = [];
    sharedPreferences.remove(AppConstants.CART_LIST);
  }

  void clearCartHistory() {
    removeCart();
    cartHistory = [];
    sharedPreferences.remove(AppConstants.CART_HISTORY_LIST);
  }
}

</code>```

I tried using some of the incartItems methods but it's not giving the result of focusing on each item
**
Cart Controller**

```<code>import 'package:get/get.dart';
import 'package:izinto/models/popular_specialty_model.dart';
import '../helpers/data/repository/cart_repo.dart';
import '../models/cart_model.dart';

class CartController extends GetxController {
  final CartRepo cartRepo;
  CartController({required this.cartRepo});
  Map<int, CartModel> _items = {};

  Map<int, CartModel> get items => _items;

  /*Only for storage and sharedPreferences*/
  List<CartModel> storageItems = [];

  void addItem(SpecialtyModel specialty, int quantity) {
    var totalQuantity = 0;
    if (_items.containsKey(specialty.id!)) {
      _items.update(specialty.id!, (value) {
        totalQuantity = value.quantity! + quantity;

        return CartModel(
          id: value.id,
          name: value.name,
          price: value.price,
          time: DateTime.now().toString(),
          img: value.img,
          type: value.type,
          material: value.material,
          quantity: value.quantity! + quantity,
          isExist: true,
          provider: value.provider,
          specialty: specialty,
        );
      });

      if (totalQuantity <= 0) {
        _items.remove(specialty.id);
      }
    } else {
      if (quantity > 0) {
        _items.putIfAbsent(specialty.id!, () {
          return CartModel(
            id: specialty.id,
            name: specialty.name,
            price: specialty.price,
            time: DateTime.now().toString(),
            img: specialty.img,
            type: specialty.type,
            material: specialty.material,
            quantity: quantity,
            isExist: true,
            provider: specialty.provider,
            specialty: specialty,
          );
        });
      } else {
        Get.snackbar(
          'Item count 0', 'Please select items to add to cart',
          // backgroundColor: AppColors.mainColor, colorText: Colors.white
        );
      }
    }
    cartRepo.addToCartList(getItems);
    update();
  }

  bool existInCart(SpecialtyModel, specialty) {
    if (_items.containsKey(specialty.id)) {
      return true;
    }
    return false;
  }

  int getQuantity(SpecialtyModel specialty) {
    var quantity = 0;
    if (_items.containsKey(specialty.id!)) {
      _items.forEach((key, value) {
        if (key == specialty.id) {
          quantity = value.quantity!;
        }
      });
    }
    return quantity;
  }

  int get totalItems {
    var totalQuantity = 0;
    _items.forEach((key, value) {
      totalQuantity += value.quantity!;
    });
    return totalQuantity;
  }

  List<CartModel> get getItems {
    return _items.entries.map((e) {
      return e.value;
    }).toList();
  }

  int get totalAmount {
    var total = 0;

    _items.forEach((key, value) {
      total += value.quantity! * value.price!;
    });
    return total;
  }

  List<CartModel> getCartData() {
    setCart = cartRepo.getCartList();
    return storageItems;
  }

  set setCart(List<CartModel> items) {
    storageItems = items;
    // print('Length of cart items ' + storageItems.length.toString());
    for (int i = 0; i < storageItems.length; i++) {
      _items.putIfAbsent(storageItems[i].specialty!.id!, () => storageItems[i]);
    }
  }

  void addToHistory() {
    cartRepo.addToCartHistoryList();
    clear();
  }

  void clear() {
    _items = {};
    update();
  }

  List<CartModel> getCartHistoryList() {
    return cartRepo.getCartHistoryList();
  }

  set setItems(Map<int, CartModel> setItems) {
    _items = {};

    _items = setItems;
  }

  void addToCartList() {
    cartRepo.addToCartList(getItems);
    update();
  }

  void clearCartHistory() {
    cartRepo.clearCartHistory();
    update();
  }
}

</code>```

This is the cart model

```<code>import 'package:izinto/models/popular_specialty_model.dart';

class CartModel {
  int? id;
  String? name;
  int? price;
  String? time;
  String? type;
  String? img;
  String? provider;
  String? material;
  int? quantity;
  bool? isExist;
  SpecialtyModel? specialty;

  CartModel(
      {this.id,
      this.name,
      this.price,
      this.time,
      this.img,
      this.type,
      this.material,
      this.quantity,
      this.isExist,
      this.provider,
      this.specialty});

  CartModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    price = json['price'];
    time = json['time'];
    img = json['img'];
    type = json['type'];
    material = json['material'];
    quantity = json['quantity'];
    isExist = json['isExist'];
    provider = json['provider'];
    specialty = SpecialtyModel.fromJson(json['specialty']);
  }

  Map<String, dynamic> toJson() {
    return {
      'id': this.id,
      'name': this.name,
      'price': this.price,
      'time': this.time,
      'img': this.img,
      'type': this.type,
      'material': this.material,
      'quantity': this.quantity,
      'isExist': this.isExist,
      'provider': this.provider,
      'specialty': this.specialty!.toJson()
    };
  }
}

```[The item should show with the quantity as in the cart page](https://i.stack.imgur.com/XRfL0.jpg)
[The item should show with the quantity as in the cart page](https://i.stack.imgur.com/GsuG7.jpg)
```

Body:
I have successfully built a home screen that can navigate to cart page and show items in cart but I now struggle to display that same item count in the home screen for each items. The methods I'm using are not suitable and competable for this task  please see the controllers included and the images attached. Idealy I want to display from home page the quantity for each specific item that has been added to cart.

// Laundry Categories as list on the home screen
GetBuilder<LaundrySpecialtyController>(
  builder: (laundrySpecialties) {
    var _specialty = laundrySpecialties.laundrySpecialtyList;
    return laundrySpecialties.isLoaded
        ? SizedBox(
            height: Dimensions.screenWidth / 3,
            width: Dimensions.screenWidth / 1.10,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount:
                  laundrySpecialties.laundrySpecialtyList.length,
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: () {
                    Get.toNamed(RouteHelper.getLaundrySpecialties(
                        index, 'home'));
                  },
                  child: Container(
                    //color: Colors.red,
                    margin: EdgeInsets.symmetric(
                        horizontal: Dimensions.screenWidth / 100),
                    width: Dimensions.screenWidth / 3.4,
                    height: Dimensions.screenHeight / 2.8,
                    child: Column(
                      children: [
                        Stack(
                          children: [
                            Container(
                              width: Dimensions.screenWidth / 3.8,
                              height: Dimensions.screenHeight / 8,
                              // margin: EdgeInsets.only(
                              //     bottom: Dimensions.height10),
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  fit: BoxFit.cover,
                                  image: AssetImage(laundrySpecialties
                                      .laundrySpecialtyList[index]
                                      .img!),
                                ),
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(
                                        Dimensions.radius15),
                                    topRight: Radius.circular(
                                        Dimensions.radius15)),
                                //color: Colors.white54,
                                // gradient: const LinearGradient(
                                //   begin: Alignment.topRight,
                                //   end: Alignment.bottomLeft,
                                //   colors: [
                                //     Colors.white,
                                //     Colors.white,
                                //   ],
                                // ),
                              ),
                            ),
                            GetBuilder<
                                    RecommendedSpecialtyController>(
                                builder: (controller) {
                              return (Container(
                                child: Positioned(
                                  right: 1,
                                  top: 1,
                                  child: GetBuilder<CartController>(
                                      builder: (cartController) {
                                    var _cartList =
                                        cartController.getItems;
                                    if (cartController.totalItems >=
                                        1) {
                                      return Container(
                                        width: 25,
                                        height: 25,
                                        decoration: BoxDecoration(
                                          color: Colors.white,
                                          boxShadow: const [
                                            BoxShadow(
                                              color:
                                                  Color(0xffB09B71),
                                              blurRadius: 2.0,
                                              offset: Offset(1, 1),
                                            ),
                                          ],
                                          borderRadius:
                                              BorderRadius.circular(
                                                  Dimensions
                                                          .height10 *
                                                      5),
                                          border: Border.all(
                                            width: 1,
                                            color: const Color(
                                                0xffB09B71),
                                          ),
                                        ),
                                        child: Center(
                                          child: SmallText(
                                            size: Dimensions.font16,
                                            text: _cartList[index]
                                                .quantity
                                                .toString(),
                                            fontWeight:
                                                FontWeight.w400,
                                            color: const Color(
                                                0xff966C3B),
                                          ),
                                        ),
                                        // AppIcon(
                                        //   size: Dimensions.iconSize26 + 2,
                                        //   iconSize: Dimensions.iconSize24,
                                        //   backgroundColor: Colors.white,
                                        //   iconColor: const Color(0xffB09B71),
                                        //   icon: Icons.add,
                                        // ),
                                      );
                                    } else {
                                      return Container();
                                    }
                                  }),
                                ),
                              ));
                            }
                                // GetBuilder<
                                //         RecommendedSpecialtyController>(
                                //     builder: (controller) {
                                //   return Container(
                                //     child: controller.totalItems >= 1
                                //         ? Positioned(
                                //             right: 1,
                                //             top: 1,
                                //             child: Container(
                                //               width: 25,
                                //               height: 25,
                                //               decoration: BoxDecoration(
                                //                 color: Colors.white,
                                //                 boxShadow: const [
                                //                   BoxShadow(
                                //                     color:
                                //                         Color(0xffB09B71),
                                //                     blurRadius: 2.0,
                                //                     offset: Offset(1, 1),
                                //                   ),
                                //                 ],
                                //                 borderRadius: BorderRadius
                                //                     .circular(Dimensions
                                //                             .height10 *
                                //                         5),
                                //                 border: Border.all(
                                //                   width: 1,
                                //                   color: const Color(
                                //                       0xffB09B71),
                                //                 ),
                                //               ),
                                //               child: Center(
                                //                 child: SmallText(
                                //                   size: Dimensions.font16,
                                //                   text: '4',
                                //                   fontWeight:
                                //                       FontWeight.w400,
                                //                   color: const Color(
                                //                       0xff966C3B),
                                //                 ),
                                //               ),
                                //               // AppIcon(
                                //               //   size: Dimensions.iconSize26 + 2,
                                //               //   iconSize: Dimensions.iconSize24,
                                //               //   backgroundColor: Colors.white,
                                //               //   iconColor: const Color(0xffB09B71),
                                //               //   icon: Icons.add,
                                //               // ),
                                //             ),
                                //           )
                                //         : Container(),
                                //   );
                                // }),
                                // Positioned(
                                //   right: 0,
                                //   left: 0,
                                //   bottom: 0,
                                //   child: Container(
                                //     width: Dimensions.screenWidth / 4,
                                //     decoration:
                                //         BoxDecoration(color: Colors.white),
                                //     child: Center(
                                //       child: SmallText(
                                //         text:
                                //             'R ${laundrySpecialties.laundrySpecialtyList[index].price!.toString()}.00',
                                //         fontWeight: FontWeight.w600,
                                //         color: const Color(0xffCFC5A5),
                                //       ),
                                //     ),
                                //   ),
                                // )
                                ),
                          ],
                        ),
                        Container(
                          width: Dimensions.screenWidth / 3.8,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.only(
                                  bottomLeft: Radius.circular(
                                      Dimensions.radius15),
                                  bottomRight: Radius.circular(
                                      Dimensions.radius15)),
                              // gradient: const LinearGradient(
                              //   begin: Alignment.bottomRight,
                              //   end: Alignment.topLeft,
                              //   colors: [
                              //     Color(0xff966C3B),
                              //     Color(0xffCFC5A5),
                              //   ],
                              // ),
                              color: Colors.white),
                          child: Center(
                            child: SmallText(
                              text: laundrySpecialties
                                  .laundrySpecialtyList[index].name!,
                              fontWeight: FontWeight.w600,
                              color: Colors.black54,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          )
        : Transform.scale(
            scale: 0.5,
            child: CircularProgressIndicator(
              color: AppColors.mainColor,
            ),
          );
  },
),

**Bellow is the laundry controller for the model
**

import 'package:get/get.dart';
import 'package:izinto/helpers/data/repository/laundry_specialty_repo.dart';

import '../models/cart_model.dart';
import '../models/popular_specialty_model.dart';
import 'cart_controller.dart';
import '../helpers/data/repository/cart_repo.dart';

class LaundrySpecialtyController extends GetxController {
  final LaundrySpecialtyRepo laundrySpecialtyRepo;
  final CartRepo cartRepo;
  LaundrySpecialtyController({required this.cartRepo,required this.laundrySpecialtyRepo});

  Map<int, CartModel> _items = {};

  List<dynamic> _laundrySpecialtyList = [];
  List<dynamic> get laundrySpecialtyList => _laundrySpecialtyList;
  late CartController _cart;

  bool _isLoaded = false;
  bool get isLoaded => _isLoaded;

  int _quantity = 0;
  int get quantity => _quantity;
  int _inCartItems = 0;
  int get inCartItems => _inCartItems + _quantity;

  get getItems => _items;

  Future<void> getLaundrySpecialtyList() async {
    Response response = await laundrySpecialtyRepo.getLaundrySpecialtyList();
    if (response.statusCode == 200) {
      print('got laundry specialties');
      // print(response.body);
      _laundrySpecialtyList = [];
      _laundrySpecialtyList
          .addAll(Specialty.fromJson(response.body).specialties);
      print(_laundrySpecialtyList);
      _isLoaded = true;
      update();
    } else {
      print('laundry not working ${response.statusCode}');
    }
  }

  void addItem(SpecialtyModel specialty, int quantity) {
    var totalQuantity = 0;
    if (_items.containsKey(specialty.id!)) {
      _items.update(specialty.id!, (value) {
        totalQuantity = value.quantity! + quantity;

        return CartModel(
          id: value.id,
          name: value.name,
          price: value.price,
          time: DateTime.now().toString(),
          img: value.img,
          type: value.type,
          material: value.material,
          quantity: value.quantity! + quantity,
          isExist: true,
          provider: value.provider,
          specialty: specialty,
        );
      });

      if (totalQuantity <= 0) {
        _items.remove(specialty.id);
      }
    } else {
      if (quantity > 0) {
        _items.putIfAbsent(specialty.id!, () {
          return CartModel(
            id: specialty.id,
            name: specialty.name,
            price: specialty.price,
            time: DateTime.now().toString(),
            img: specialty.img,
            type: specialty.type,
            material: specialty.material,
            quantity: quantity,
            isExist: true,
            provider: specialty.provider,
            specialty: specialty,
          );
        });
      } else {
        Get.snackbar(
          'Item count 0', 'Please select items to add to cart',
          // backgroundColor: AppColors.mainColor, colorText: Colors.white
        );
      }
    }
    cartRepo.addToCartList(getItems);
    update();
  }

  void setQuantity(bool isIncrement) {
    if (isIncrement) {
      _quantity = checkQuantity(_quantity + 1);
      // print('number of items ' + _quantity.toString());
    } else {
      _quantity = checkQuantity(_quantity - 1);
      // print('items reduced to ' + _quantity.toString());
    }
    update();
  }

  int checkQuantity(int quantity) {
    if ((_inCartItems + quantity) < 0) {
      Get.snackbar(
        'Item count 0', 'You don\'t have items',
        // backgroundColor: AppColors.mainColor, colorText: Colors.white
      );
      if (_inCartItems > 0) {
        _quantity = -_inCartItems;
        return _quantity;
      }
      return 0;
    } else if ((_inCartItems + quantity) > 20) {
      Get.snackbar('Item count 20', 'Maximum number of items selected');
      return 20;
    } else {
      return quantity;
    }
  }
}

The cart repo

import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../models/cart_model.dart';
import '../../../utils/app_constants.dart';

class CartRepo {
  final SharedPreferences sharedPreferences;
  CartRepo({required this.sharedPreferences});

  List<String> cart = [];
  List<String> cartHistory = [];

  void addToCartList(List<CartModel> cartList) {
    sharedPreferences.remove(AppConstants.CART_LIST);
    sharedPreferences.remove(AppConstants.CART_HISTORY_LIST);
    var time = DateTime.now().toString();
    cart = [];
    /*
      convert objects to string because shared preferences only accepts string
     */

    cartList.forEach((element) {
      element.time = time;
      return cart.add(jsonEncode(element));
    });

    sharedPreferences.setStringList(AppConstants.CART_LIST, cart);
    // print(sharedPreferences.getStringList(AppConstants.CART_LIST));
    // getCartList();
  }

  List<CartModel> getCartList() {
    List<String> carts = [];
    if (sharedPreferences.containsKey(AppConstants.CART_LIST)) {
      carts = sharedPreferences.getStringList(AppConstants.CART_LIST)!;
      // print('inside getCartList ' + carts.toString());
    }
    List<CartModel> cartList = [];

    carts.forEach(
        (element) => cartList.add(CartModel.fromJson(jsonDecode(element))));

    return cartList;
  }

  List<CartModel> getCartHistoryList() {
    if (sharedPreferences.containsKey(AppConstants.CART_HISTORY_LIST)) {
      // cartHistory = [];
      cartHistory =
          sharedPreferences.getStringList(AppConstants.CART_HISTORY_LIST)!;
    }

    List<CartModel> cartListHistory = [];
    cartHistory.forEach((element) =>
        cartListHistory.add(CartModel.fromJson(jsonDecode(element))));
    return cartListHistory;
  }

  void addToCartHistoryList() {
    if (sharedPreferences.containsKey(AppConstants.CART_HISTORY_LIST)) {
      cartHistory =
          sharedPreferences.getStringList(AppConstants.CART_HISTORY_LIST)!;
    }
    for (int i = 0; i < cart.length; i++) {
      print('history list ' + cart[i]);
      cartHistory.add(cart[i]);
    }
    removeCart();
    sharedPreferences.setStringList(
        AppConstants.CART_HISTORY_LIST, cartHistory);
    print('The length of history list is ' +
        getCartHistoryList().length.toString());
    for (int j = 0; j < getCartHistoryList().length; j++) {
      print('The time for the order is ' +
          getCartHistoryList()[j].time.toString());
    }
  }

  void removeCart() {
    cart = [];
    sharedPreferences.remove(AppConstants.CART_LIST);
  }

  void clearCartHistory() {
    removeCart();
    cartHistory = [];
    sharedPreferences.remove(AppConstants.CART_HISTORY_LIST);
  }
}

I tried using some of the incartItems methods but it's not giving the result of focusing on each item
**
Cart Controller**

import 'package:get/get.dart';
import 'package:izinto/models/popular_specialty_model.dart';
import '../helpers/data/repository/cart_repo.dart';
import '../models/cart_model.dart';

class CartController extends GetxController {
  final CartRepo cartRepo;
  CartController({required this.cartRepo});
  Map<int, CartModel> _items = {};

  Map<int, CartModel> get items => _items;

  /*Only for storage and sharedPreferences*/
  List<CartModel> storageItems = [];

  void addItem(SpecialtyModel specialty, int quantity) {
    var totalQuantity = 0;
    if (_items.containsKey(specialty.id!)) {
      _items.update(specialty.id!, (value) {
        totalQuantity = value.quantity! + quantity;

        return CartModel(
          id: value.id,
          name: value.name,
          price: value.price,
          time: DateTime.now().toString(),
          img: value.img,
          type: value.type,
          material: value.material,
          quantity: value.quantity! + quantity,
          isExist: true,
          provider: value.provider,
          specialty: specialty,
        );
      });

      if (totalQuantity <= 0) {
        _items.remove(specialty.id);
      }
    } else {
      if (quantity > 0) {
        _items.putIfAbsent(specialty.id!, () {
          return CartModel(
            id: specialty.id,
            name: specialty.name,
            price: specialty.price,
            time: DateTime.now().toString(),
            img: specialty.img,
            type: specialty.type,
            material: specialty.material,
            quantity: quantity,
            isExist: true,
            provider: specialty.provider,
            specialty: specialty,
          );
        });
      } else {
        Get.snackbar(
          'Item count 0', 'Please select items to add to cart',
          // backgroundColor: AppColors.mainColor, colorText: Colors.white
        );
      }
    }
    cartRepo.addToCartList(getItems);
    update();
  }

  bool existInCart(SpecialtyModel, specialty) {
    if (_items.containsKey(specialty.id)) {
      return true;
    }
    return false;
  }

  int getQuantity(SpecialtyModel specialty) {
    var quantity = 0;
    if (_items.containsKey(specialty.id!)) {
      _items.forEach((key, value) {
        if (key == specialty.id) {
          quantity = value.quantity!;
        }
      });
    }
    return quantity;
  }

  int get totalItems {
    var totalQuantity = 0;
    _items.forEach((key, value) {
      totalQuantity += value.quantity!;
    });
    return totalQuantity;
  }

  List<CartModel> get getItems {
    return _items.entries.map((e) {
      return e.value;
    }).toList();
  }

  int get totalAmount {
    var total = 0;

    _items.forEach((key, value) {
      total += value.quantity! * value.price!;
    });
    return total;
  }

  List<CartModel> getCartData() {
    setCart = cartRepo.getCartList();
    return storageItems;
  }

  set setCart(List<CartModel> items) {
    storageItems = items;
    // print('Length of cart items ' + storageItems.length.toString());
    for (int i = 0; i < storageItems.length; i++) {
      _items.putIfAbsent(storageItems[i].specialty!.id!, () => storageItems[i]);
    }
  }

  void addToHistory() {
    cartRepo.addToCartHistoryList();
    clear();
  }

  void clear() {
    _items = {};
    update();
  }

  List<CartModel> getCartHistoryList() {
    return cartRepo.getCartHistoryList();
  }

  set setItems(Map<int, CartModel> setItems) {
    _items = {};

    _items = setItems;
  }

  void addToCartList() {
    cartRepo.addToCartList(getItems);
    update();
  }

  void clearCartHistory() {
    cartRepo.clearCartHistory();
    update();
  }
}

This is the cart model

import 'package:izinto/models/popular_specialty_model.dart';

class CartModel {
  int? id;
  String? name;
  int? price;
  String? time;
  String? type;
  String? img;
  String? provider;
  String? material;
  int? quantity;
  bool? isExist;
  SpecialtyModel? specialty;

  CartModel(
      {this.id,
      this.name,
      this.price,
      this.time,
      this.img,
      this.type,
      this.material,
      this.quantity,
      this.isExist,
      this.provider,
      this.specialty});

  CartModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    price = json['price'];
    time = json['time'];
    img = json['img'];
    type = json['type'];
    material = json['material'];
    quantity = json['quantity'];
    isExist = json['isExist'];
    provider = json['provider'];
    specialty = SpecialtyModel.fromJson(json['specialty']);
  }

  Map<String, dynamic> toJson() {
    return {
      'id': this.id,
      'name': this.name,
      'price': this.price,
      'time': this.time,
      'img': this.img,
      'type': this.type,
      'material': this.material,
      'quantity': this.quantity,
      'isExist': this.isExist,
      'provider': this.provider,
      'specialty': this.specialty!.toJson()
    };
  }
}

```[The item should show with the quantity as in the cart page](https://i.stack.imgur.com/XRfL0.jpg)
[The item should show with the quantity as in the cart page](https://i.stack.imgur.com/GsuG7.jpg)