Home > Back-end >  For two different widgets, how do I get the boolean value in one from the second widget?
For two different widgets, how do I get the boolean value in one from the second widget?

Time:08-18

I am using two different widgets and need some data from one widget to another. This data(boolean isGoalAchieved) is calculated in goal_card_detail.dart widget and I need to use it to rename button in goal_card_data.dart page. How can I achieve this?

goal_card_details.dart

import 'package:app/src/common.dart';
import 'package:app/src/utils/utils.dart';

class GoalCardDetails extends StatelessWidget {
  final double goalAmount;
  final double currentBalance;
  final double monthlyAmount;
  final bool isWaitingForApproval;

  const GoalCardDetails({
    Key? key,
    required this.goalAmount,
    required this.currentBalance,
    required this.monthlyAmount,
    required this.isWaitingForApproval,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final l10n = context.l10n;
    final TextStyle titleStyle = Theme.of(context).textTheme.substitleBold;
    final TextStyle subtitleStyle = Theme.of(context).textTheme.overlineRegular;
    final double remainingAmount = goalAmount - currentBalance;
    final int remainingPeriod = (remainingAmount / monthlyAmount).ceil();
    late String remainingTitle;

    final bool isGoalAchieved = remainingPeriod <= 0;

    if (isGoalAchieved) {
      remainingTitle = l10n.goalAchieved;
    } else {
      remainingTitle = AppUtils.periodToDoubleYears(context,
          periodInMonths: remainingPeriod);
    }

    final String monthlyAmountAsFixed = monthlyAmount.toStringAsFixed(2);
    List<String> monthlyAmountParts = monthlyAmountAsFixed.split('.');

    final String monthlyAmountText = monthlyAmountParts.last == '00'
        ? monthlyAmountParts.first
        : monthlyAmountAsFixed;

    Text _getTitle(String title) => Text(title, style: titleStyle);

    ListTile _getListTile({required Widget title, String? subtitle}) {
      return ListTile(
        dense: true,
        horizontalTitleGap: 0,
        minVerticalPadding: 0,
        visualDensity: const VisualDensity(horizontal: 0, vertical: -4),
        contentPadding: EdgeInsets.zero,
        title: title,
        subtitle:
            subtitle != null ? Text(subtitle, style: subtitleStyle) : null,
      );
    }

    return Column(
      children: [
        if (!isWaitingForApproval)
          _getListTile(
            title: _getTitle(remainingTitle),
            subtitle: !isGoalAchieved ? l10n.remainingSubtitle : null,
          ),
        _getListTile(
          title: _getTitle('$monthlyAmountText€'),
          subtitle: l10n.monthlyAmountSubtitle,
        )
      ],
    );
  }
}

goal_card_data.dart


import 'package:app/models/ModelProvider.dart';
import 'package:app/src/common.dart';
import 'package:app/src/common_widgets/app_buttons.dart';
import 'package:app/src/common_widgets/app_show_alert_dialog.dart';
import 'package:app/src/features/extraction_request/body.dart';
import 'package:app/src/features/goals/card/goal_card.dart';
import 'package:app/src/utils/utils.dart';

class GoalCardData extends StatelessWidget {
  final Objective goal;

  const GoalCardData({
    Key? key,
    required this.goal,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final AppLocalizations l10n = context.l10n;

    final bool isStarted = goal.status != ObjectiveStatuses.CREATED;

    final bool isWaitingForApproval =
        goal.status == ObjectiveStatuses.WITHDRAW_PENDING_APPROVAL &&
            goal.status != ObjectiveStatuses.CREATED;

    final goalAmount = goal.objectiveSalaryGross * goal.objectivePeriodInMonths;
    final currentBalance = goal.objectiveSalaryGross / 1;

    return Stack(
      alignment: Alignment.topCenter,
      children: [
        if (isWaitingForApproval) const GoalCardPendingLabel(),
        Padding(
          padding:
              const EdgeInsets.only(top: 24, right: 24, bottom: 22, left: 24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              GoalCardTitle(
                  title: goal.title,
                  subtitle: AppUtils.periodToYearsAndMonths(
                    context,
                    period: goal.objectivePeriodInMonths,
                  )),
              Padding(
                padding:
                    const EdgeInsets.symmetric(horizontal: 0, vertical: 24),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                      child: GoalCardRadialGauge(
                          percentage: currentBalance / goalAmount),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.only(left: 8.0),
                        child: GoalCardDetails(
                          goalAmount: goalAmount,
                          currentBalance: currentBalance,
                          monthlyAmount: goal.objectiveDepositionGross,
                          isWaitingForApproval: isWaitingForApproval,
                        ),
                      ),
                    )
                  ],
                ),
              ),
              ButtonBar(
                alignment: MainAxisAlignment.spaceBetween,
                buttonPadding: const EdgeInsets.all(0),
                children: [
                  AppButtons.button(
                      onPressed: () => AppUtils.snackBarNotImplemented(context),
                      outline: true,
                      appButtonSize: AppButtonsSize.small,
                      child: Text(l10n.buttonDetails)),
                  if (isStarted)
                    AppButtons.button(
                      onPressed: () => appShowAlertDialog(
                        context,
                        dialogType: AppAlerdDialogType.startSavingDialog,
                      ),
                      appButtonSize: AppButtonsSize.small,
                      child: Text(context.l10n.buttonStartGoal),
                    )
                  else if (!isWaitingForApproval && currentBalance > 0)
                    AppButtons.button(
                        onPressed: () {
                          Navigator.of(context)
                              .pushNamed(ExtractionBody.routeName);
                        },
                        child: Text(l10n.buttonWithdraw))
                  // else if (isWaitingExtractionApproved)
                  //   AppButtons.button(
                  //       onPressed: () {
                  //         Navigator.of(context)
                  //             .pushNamed(ExtractionBody.routeName);
                  //       },
                  //       child: Text(l10n.buttonExtractionRequest))
                ],
              )
            ],
          ),
        )
      ],
    );
  }
}


As I said, my goal is to add AppButtons based on the boolean "isGoalAchieved" in goal_card_details.

like this;


   else if (isGoalAchieved)
                     AppButtons.button(
                         onPressed: () {
                  Navigator.of(context)
                             .pushNamed(ExtractionBody.routeName);
                       },
                       child: Text(l10n.buttonExtractionRequest))

CodePudding user response:

You can pass the boolean or any value using the constructor.

or you can also pass arguments if you need value in navigation

You can check this for how to pass string/bool/Any value and access it

CodePudding user response:

both your class is StatelessWidget , then just create this function inside goal_card_data.dart . no need to calculate in another class

// i just copied your calculation from  goal_card_details.dart

 final double remainingAmount = goalAmount - currentBalance;
 final int remainingPeriod = (remainingAmount / monthlyAmount).ceil();

 bool isgoalachived = isGoalAchieved = remainingPeriod <= 0;

 return Stack(
      alignment: Alignment.topCenter,
      children: [
        if (isWaitingForApproval) const GoalCardPendingLabel(),

        .........................

        else if (isgoalachived ) {}

  • Related