Skip to content

Magento 2 Set Shipping Method Programatically

I am trying to set Shipping Method Progrmatically but getting following error.
The shipping method is missing. Select the shipping method and try again.

foreach ($quote->getAllAddresses() as $address) {
            // Build grand total.
        $grandTotal = (($finalPrice + $shipping + $tax) - $discount);
        $baseGrandTotal =  $this->convertPrice($grandTotal);
        $baseFinalPrice =  $this->convertPrice($finalPrice);
        $baseDiscount =  $this->convertPrice($discount);
        $baseTax =  $this->convertPrice($tax);

        //$address->setFreeShipping(true); //tried this but not getting set

        $address->setShippingMethod('flatrate_flatrate'); //tried this getting error
        $address->setCollectShippingRates(true);


        $address->setBaseSubtotal($baseFinalPrice);
        $address->setSubtotal($finalPrice);
        $address->setDiscountAmount($discount);
        $address->setBaseDiscountAmount($baseDiscount);
        $address->setTaxAmount($tax);
        $address->setBaseTaxAmount($baseTax);
        $address->setBaseGrandTotal($baseGrandTotal);
        $address->setGrandTotal($grandTotal);
        $address->save();

}