Error function get_cart() on null in theme function file

I have added this code in theme function to add quantity
//add qunitty

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
    if (!is_page('wishlist')) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
        // Access the cart items
        $in_cart = false;
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $product_id = $cart_item['product_id'];
            $quantity = $cart_item['quantity'];
            if($product_id == $product->get_ID()){
                $in_cart = true;
                break;
            }
        }
        // If we have match update quantity
        if($in_cart) {
            $html .= woocommerce_quantity_input( array('input_value' => $quantity), $product, false );
        } else {
            $html .= woocommerce_quantity_input( array(), $product, false );
        }
        $html .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
        $html .= '</form>';
    }
    return $html;
}
return $html;
}

But I got this error in theme log-file

function get_cart() on null

What I’m doing wrong?