build method

  1. @override
Widget build(
  1. BuildContext context
)
override

Describes the part of the user interface represented by this widget.

The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes). This method can potentially be called in every frame and should not have any side effects beyond building a widget.

The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.

Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor and from the given BuildContext.

The given BuildContext contains information about the location in the tree at which this widget is being built. For example, the context provides the set of inherited widgets for this location in the tree. A given widget might be built with multiple different BuildContext arguments over time if the widget is moved around the tree or if the widget is inserted into the tree in multiple places at once.

The implementation of this method must only depend on:

If a widget's build method is to depend on anything else, use a StatefulWidget instead.

See also:

  • StatelessWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context) {
  // some ui sizing variables
  const double _spacing = 30.0;
  const double _padding = 18.0;
  const double _dividerThickness = 1.2;
  const double _collapsedAppBarHeight = 100;

  // reference to whether or not the sliverAppBar is open or closed
  bool _isOpen = false;

  // Calculate the total charge amount
  int _priceCents = 0;
  for (var item in priceItems) {
    _priceCents += item.totalPriceCents;
  }

  // create a new list of items
  final List<PriceItem> _priceItems = priceItems;

  // add the final price as a line item
  _priceItems.add(
      PriceItem(name: 'Total', quantity: 1, totalPriceCents: _priceCents));

  // convert the calculated total to a string
  final String _priceString =
      (_priceCents.toDouble() / 100).toStringAsFixed(2);

  // calculate the height of the expanded appbar based on the total number
  // of line items to display.
  final double _expHeight = (_priceItems.length * 50) + 165;

  // Calculate the init height the scroll should be set to to properly
  // display the title and amount to be charged
  final double _initHeight = _expHeight - (_collapsedAppBarHeight + 30.0);

  // create a ScrollController to listen to whether or not the appbar is open
  final ScrollController _scrollController =
      ScrollController(initialScrollOffset: _initHeight);

  // create a key to modify the details text based on appbar expanded status
  final GlobalKey<_StatefullWrapperState> textKey =
      GlobalKey<_StatefullWrapperState>();

  // set the text that should be display based on the appbar status
  const Widget textWhileClosed = Text(
    'View Details',
    style: TextStyle(fontSize: 12.0),
  );
  const Widget textWhileOpen = Text(
    'Hide Details',
    style: TextStyle(fontSize: 12.0),
  );

  // add the listener to the scroll controller mentioned above
  _scrollController.addListener(() {
    final bool result = (_scrollController.offset <= (2 * _initHeight / 3));
    if (result != _isOpen) {
      _isOpen = result;
      if (_isOpen) {
        textKey.currentState?.setchild(textWhileOpen);
      } else {
        textKey.currentState?.setchild(textWhileClosed);
      }
    }
  });

  return CustomScrollView(
    controller: _scrollController,
    slivers: [
      SliverAppBar(
        snap: false,
        pinned: false,
        floating: false,
        backgroundColor: Colors.grey.shade50,
        collapsedHeight: _collapsedAppBarHeight,
        // set to false to prevent undesired back arrow
        automaticallyImplyLeading: false,
        title: Row(
          children: [
            SizedBox(
              width: 40,
              child: (onBack != null)
                  ? IconButton(
                      onPressed: () => onBack!(),
                      icon: const Icon(
                        Icons.keyboard_arrow_left_outlined,
                        color: Colors.black,
                      ))
                  : null,
            ),
            Expanded(
                child: Text(
              payToName.length < 16 ? '$payToName Checkout' : payToName,
              textAlign: TextAlign.center,
              style: const TextStyle(fontSize: 26, color: Colors.black),
            )),
            const SizedBox(
              width: 40,
            ),
          ],
        ),
        bottom: PreferredSize(
          preferredSize: const Size(120.0, 32.0),
          child: GestureDetector(
            onTap: () {
              if (_isOpen) {
                _scrollController.jumpTo(_initHeight);
              } else {
                _scrollController.jumpTo(0);
              }
            },
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text('Charge Amount '),
                Text(
                  '\$$_priceString',
                  style: const TextStyle(
                      color: Colors.green,
                      fontSize: 24,
                      fontWeight: FontWeight.bold),
                ),
                _StatefullWrapper(
                  key: textKey,
                  initChild: textWhileClosed,
                ),
              ],
            ),
          ),
        ),
        expandedHeight: _expHeight,
        flexibleSpace: FlexibleSpaceBar(
          centerTitle: true,
          background: Padding(
            padding: const EdgeInsets.fromLTRB(16.0, 80, 16.0, 0),
            child: Column(
              children: [
                const SizedBox(
                  height: 30,
                ),
                Column(
                  children: _priceItems
                      .map(
                          (priceItem) => _PriceListItem(priceItem: priceItem))
                      .toList(),
                ),
              ],
            ),
          ),
        ),
      ),
      SliverList(
        delegate: SliverChildListDelegate(
          [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Column(
                children: [
                  if (displayNativePay) const SizedBox(height: _spacing * 2),
                  if (displayNativePay)
                    ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        primary: Colors.black,
                        minimumSize: const Size(double.infinity, 50),
                      ),
                      onPressed: () {
                        if (onNativePay != null) {
                          onNativePay!();
                        }
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            margin: const EdgeInsets.fromLTRB(0, 0, 4, 0),
                            height: 16,
                            width: 16,
                            child: Image.asset(
                                isApple
                                    ? 'assets/images/apple-32.png'
                                    : 'assets/images/G_mark_small.png',
                                package: 'checkout_screen_ui'),
                          ),
                          Text(
                            'Pay',
                            style: TextStyle(
                                fontSize: 18,
                                fontWeight: isApple
                                    ? FontWeight.w500
                                    : FontWeight.w400,
                                color: Colors.white),
                          )
                        ],
                      ),
                    ),
                  if (_displayOrCash)
                    const SizedBox(
                      height: _spacing,
                    ),
                  if (_displayOrCash)
                    Row(
                      children: const [
                        Expanded(
                          child: Divider(
                            thickness: _dividerThickness,
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: _padding),
                          child: Text('Or pay with Cash'),
                        ),
                        Expanded(
                          child: Divider(
                            thickness: _dividerThickness,
                          ),
                        ),
                      ],
                    ),
                  if (displayCashPay) const SizedBox(height: _spacing),
                  if (displayCashPay)
                    ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        primary: Colors.green,
                        minimumSize: const Size(double.infinity, 50),
                      ),
                      onPressed: () {
                        if (onCashPay != null) {
                          onCashPay!();
                        }
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            margin: const EdgeInsets.fromLTRB(0, 0, 4, 0),
                            height: 32,
                            width: 32,
                            child: Image.asset(
                                'assets/images/pay_option_cash.png', //assets/images/pay_option_cash.png
                                package: 'checkout_screen_ui'),
                          ),
                          Text(
                            'Cash',
                            style: TextStyle(
                                fontSize: 18,
                                fontWeight: isApple
                                    ? FontWeight.w500
                                    : FontWeight.w400,
                                color: Colors.white),
                          )
                        ],
                      ),
                    ),
                  if (_displayCashPrice)
                    const Padding(
                      padding: EdgeInsets.only(top: 12.0, bottom: 8.0),
                      child: Text(
                        'Discounted price of',
                        style: TextStyle(
                            fontStyle: FontStyle.italic,
                            color: Colors.grey,
                            fontSize: 12),
                      ),
                    ),
                  if (_displayCashPrice)
                    Text(
                      '\$${cashPrice!.toStringAsFixed(2)}',
                      style: const TextStyle(
                          fontStyle: FontStyle.italic, color: Colors.grey),
                    ),
                  if (_displayOrCard)
                    const SizedBox(
                      height: _spacing,
                    ),
                  if (_displayOrCard)
                    Row(
                      children: const [
                        Expanded(
                          child: Divider(
                            thickness: _dividerThickness,
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: _padding),
                          child: Text('Or pay with Card'),
                        ),
                        Expanded(
                          child: Divider(
                            thickness: _dividerThickness,
                          ),
                        ),
                      ],
                    ),
                  const SizedBox(
                    height: _spacing,
                  ),
                  CreditCardForm(
                    formKey: formKey,
                    onCardPay: (CardFormResults results) =>
                        onCardPay(results),
                    displayEmail: displayEmail,
                    lockEmail: lockEmail,
                    initBuyerName: initBuyerName,
                    initEmail: initEmail,
                    initPhone: initPhone,
                    payBtnKey: payBtnKey,
                    displayTestData: displayTestData,
                  ),
                  footer ?? const SizedBox(height: 120),
                ],
              ),
            ),
          ],
        ),
      ),
    ],
  );
}