Barcelona has been a fashionable and intensely fashion-conscious city for many years now. In 1966, when I first went there, it was rather different. Non-Catalans thought it was provincial, like the rest of Spain. Nobody outside Catalonia, and by no means everyone inside it, would have agreed with the argument of Barcelona and Modernity: Gaudí to Dali, the new show opening at the Met in New York next month, which is essentially that, between 1870 and 1920, Barcelona was intermittently a great cultural centre, to be reckoned as one of the essential proving grounds of modernism.

So many Americans, and even some Europeans, were used to thinking that modernism had two capitals: Paris and New York. You could hardly even call this view simplified. It was blind. It left out Vienna. It ignored London. It downplayed Berlin. And as for Barcelona, what did I know about it, in my semi-virginal ignorance during the mid-1960s? That three decades before, in the name of the doomed Spanish republic, it had stubbornly resisted General Franco and paid a heavy, bitter price for it. That George Orwell had written a book about it called Homage to Catalonia; that in it he had been spectacularly wrong in dissing the admittedly very weird architect Antoni Gaudí, claimed by the French surrealists, who had designed that enormous penitential church apparently made of melted candle-wax and chicken-guts, the Sagrada Familia. That was about it. Forty years ago, the foreigner's knowledge of Barcelona was so embarrassingly slight that we weren't even embarrassed by it.

The 1,500 years of the city's existence had produced only five names that came readily to mind. There was Gaudí, and the century's greatest cellist, Pablo Casals. There were the painters Salvador Dali, Joan Miro and Pablo Picasso, who, although he was born in Malaga and spent most of his long life in France, had become a sort of honorary Catalan because he studied at the art school in Barcelona. But even the appreciation of Dali and Miro was considerably distorted because those who loved them didn't appreciate their Catalan roots. Miro, for instance, was a country boy to whose imagery the folk culture of Catalonia, with its obsessive concentration on shit as a rural sacrament, was absolutely basic; such meanings were not at all obvious when seen from Paris or New York.

Of other Catalan artists who were older than Picasso, and were at the time rather his superiors, such as that superbly fluent and piercing draughtsman Ramon Casas, we were quite ignorant. We got Gaudí wrong because we knew little or nothing about his deeply Catalan roots, his obsession with craft culture and his deep, Catholic piety. We took him for a proto- surrealist weirdo, which trivialises his achievement. We had no idea where to put him, although he was so manifestly radical an artist, because we were too blinded by the rhetoric of the 1960s to imagine a radicalism that was both right-wing and intensely fruitful.

On the other hand, we probably wouldn't have recognised the name of an almost equally great architect of the late 19th century, Lluis Domenech i Montaner, or even been able to pronounce that of Josep Puig i Cadafalch, one of the most erudite and sophisticated designers ever to work in Europe. Of course, none of these ever built anything for a non-Catalan patron.

We knew little or nothing about the magnificent murals by Romanesque artists salvaged from the collapsing churches of the Pyrenees and transferred to the National Museum of Catalan Art - which are to fresco painting what the images of Ravenna are to the art of mosaic.

Barcelona hadn't produced significant painting when the siglo d'oro, the "golden century" of Velazquez and Ribera, was at its height. Its turn would begin to come at the end of the 1800s with what Catalans called their Renaixenca - not "renaissance" in the Italian sense, but certainly a rebirth of energy, in which Catalan painters like Casas and Santiago Rusinol hooked into the energies of fin-de-siecle Paris (a train journey away to the north) and came up with their own realist movement: laconic, gritty and often infused with political reportage. Its centres were two: a Parisian boite called the Moulin de la Galette, and a bohemian bar- restaurant in Barcelona named Els Quatre Gats (the Four Cats). Revolt, and the smell of dynamite, was in the Catalan air as in the Parisian; indeed, through the 1890s, Barcelona was the capital of world anarchism, and the sporadic roar of explosions ratcheted up the anxieties of its middle classes then as the thought of Islamist terrorism does now. An outstanding painting by Casas was Garrote Vil, 1894, showing the execution of a young star of the anarchist movement, Santiago Salvador, whose bomb had slaughtered several dozen opera-goers during a performance of Rossini's William Tell. An artist of marvellous facility, Casas moved with ease between the lower and upper crusts of Barcelona, becoming the city's chief social recorder. His self-portrait, pedalling a tandem bicycle with his friend Pere (Peter) Romeu, the lugubrious, rabbit-toothed manager of the Four Cats, is one of the indelible emblems of the period.

A good deal of expert, witty and sometimes moving work came out of the Catalan Renaixenca, though it certainly produced no painter as great as Adolf von Menzel in Germany, Isaac Levitan in Russia or Frederic Church in the United States. But it did create an extraordinary city plan, the Eixample, or "enlargement", of Barcelona into the grid of equal squares that surrounds the medieval city. The Eixample was the ancestor of all grid cities to come after the 1860s, including Manhattan. Its visionary designer was Ildefons Cerda. Trained as a civil engineer in Madrid, he had written a treatise on the appalling housing conditions of the old city, which he was determined to change. While the bards of 19th-century Catalonia - obsessed by the desire to revive their lost cultural independence - were warbling nostalgically about the need to bring back the glories of the Catalan middle ages, it was clear that in terms of hygiene and social services, the ordinary working folk of Barcelona inside the muralles - the corset of walls in which the Bourbons had imprisoned the rebellious, working-class ciutat vella, or old core of medieval-to-18th-century Barcelona - had never escaped them. And because of the explosive industrial growth of their city, conditions were getting worse all the time.

Cerda would change this. He envisioned his new city, built on the sloping plain outside the muralles, as a perfect fabric of identically sized blocks, covering nine square kilometres with their regimented grid. It was therefore quite different to Baron Haussmann's plans for Paris. Haussmann needed to demolish an ancient city. Cerda had nothing to demolish. He had the urbanist's dream, a blank slate. Cerda thought of each of his blocks as a social cross-section: there would be no "good" and no "bad" end of town, and the cellular plan could be expanded forever. Only a third of each block, about 5,000 square metres, would be built on; the rest would be patio and green space. Cerda's standard block would have 700,000 square feet of built floor space and a maximum height of 65 feet. Over the next century such restrictions went by the board, particularly during the Franco era. Developers and corrupt officials made a travesty of Cerda's plan.

Nevertheless, the new city, from the 1870s on, became a treasury of new architecture, which fused two seemingly incompatible desires: to be modern, and to recapitulate the glories of the Catalan past. Painting had not done this.

But building would.

Llu is Domenech i Montaner, born 1849, died 1923, was the great theorist and the practical all-rounder of Catalan architectural nationalism. He was widely travelled, deeply read, and a scholar of everything from iron forging to medieval heraldry. This protean figure was the son of a Barcelona bookbinder. He was politically more conservative than William Morris in England, but a somewhat analogous figure and just as delightful a personality.

Domenech was absorbed by the problem of defining a national architecture, a necessary thing for Catalans if they were to assert their difference from the rest of Spain. All talk about design and building, he declared in a manifesto published in 1878, has to centre on this. In writing, we can say who we are and what we aspire to be. We can imagine painting making similar declarations. But can architecture do it? And if so, how?

We modern Europeans, he argued, live in a culture which is alive but also a museum. Through it we get access to a huge variety of prototypes and ideas - Greek, Gothic, Vitruvian, Indian, Egyptian and Islamic building forms, and we ought to be proficient in all of them. But none of them constitutes our central myth, technology itself. In a world of iron and glass, of chemistry and electricity, Domenech wrote, "everything heralds the appearance of a new era for architecture". Spain, he went on, has two great wells of architecture. One is the Romanesque and Gothic in Catalonia. The other, in the south, owing its existence to the Arabs, is Islamic: Granada, Seville, Cordoba. Neither excludes the other and local patriotism must not make it seem to. A truly national architecture has to draw strength from both, but it will not do so just by copying.

A wonderful example of what he meant was in fact one of his earliest buildings, designed for the 1888 Universal Exposition: the cafe-restaurant, now converted into a zoological museum. It looks medieval, with its crenellations and white ceramic shields, but these are actually an early form of pop art, advertising Catalan produce and even the drinks the cafe was offering its customers. And the building itself is made of plain brick and industrial iron. The stretch between its medievalism and the modernity of its materials makes it an early modernist landmark. To use plain brick in a festive urban building in 1888 was close to a breach of etiquette. The very word for brick in Catalan, totxo, also meant "ugly" or "stupid". But Domenech thought brick ought to be used plainly. To him, as to Gaudí and to their younger colleague Puig i Cadafalch, it was clar i catala, "clear and Catalan". The same with iron, about whose unembellished use young Domenech was just as explicit. He let his iron framing show. He also used painted, glazed and moulded ornament, but never to obscure the structure underneath. This reached an extreme in the ceramic flowers on the structural grid of his masterpiece of the early 1900s, the Palau de la Musica Catalana, or "Palace of Catalan Music".

This amazing building had been designed to house a choral society, formed to revive and glorify Catalan folk music - canco popular. This in turn would serve as a bridge to classical music, musica universal - Bach, Beethoven, Handel, Berlioz, Mahler and especially (the favourite musical obsession of educated Catalans) Wagner, who was regarded as an honorary Catalan - "an instrument and a sign of national culture", as one Catalan put it. They saw in his work for Germany an achieved parallel to their own desire to create a myth of national identity for Catalonia. His holy mountains, like Montsalvat, Parsifal's birthplace, were their holy mountains.

Moreover, the age of Wagner's themes contrasted with the daring newness of his forms. Wagner had meant the Ring cycle to be the founding epic of Bavaria. Its mission was to describe the identity of the German race. Likewise, the Renaixenca was obsessed by the supposed uniqueness of the Catalan people. It sought its modernism in an idealised, mythic past. No wonder Catalanists adopted Wagner as a guide to combining myths of a legendary past with the overarching myth of progress and innovation. Wagner's vision of the "total work of art", in which all media played a part, had a strong allure for architects who were working out of a deep craft base to combine the talents of painters, ceramists, metalsmiths, joiners, mosaicists and glaziers. All these are present at an abnormally rich level of display in the Palau de la Musica, the most Wagnerian building in Barcelona - or the world. It is an ultimate showcase building, its vaults sheathed in pale ochre and aquamarine embossed tiles, its surfaces brilliant with roses the size of cabbages, its staircases shining with squat golden-glass balusters. But not even these prepare you for the auditorium, a large box of pink stained glass. From the middle of its ceiling a huge, spectacular skylight, or claraboia, swells down, an inverted bell or pendulous breast. Its motif is a circle of angelic choristers, diffusing a soft pink-and-blue radiance from on high.

In his architecture Domenech quoted incessantly, but he did so with great intelligence and verve. So did other Catalan architects, his contemporaries, like Puig i Cadafalch, who fell under the inspiration of Dutch townhousing and, for a chocolate millionaire named Amatller, built on Passeig de Gracia a fantastically rich variant on one of those stepped facades that gaze down on the canals of Amsterdam. Its tiles, blue, cream, pink and oxblood, shine and twinkle in the Spanish sun in a way that no Dutch burgher would have tolerated. And its chromatic richness shines out against the uniformity of the Eixample 's grid in a way that Ildefons Cerda would not have liked either. Puig hated the uniformity of the Eixample, and was not the only architect who did his best to disrupt it.

And though no museum can borrow whole buildings, what will be shown at the Met is the utterly delectable character of high-bourgeois social surface: the curling inlaid furniture of brilliant cabinet-makers like Gaspar Homar, the delicate jewellery of Lluis Masriera, the fabrics, ceramics and bronzes that gave such iridescent texture to things of domestic use. Though Barcelona's later devotion to a more strict, International-style modernism is also set before you in lavish detail in this show, and there is a brilliant, furious sampling of republican propaganda connected to the civil war, it's inevitable that the belle-epoque material seems the most fascinating and idiosyncratic.

Some things were designed by the most famous architect - and for most people, especially foreign visitors, the single most famous human being - that Barcelona ever produced, who was killed by a tram one June day in 1926. Only later, as he lay dying in the public hospital of Sant Creu, was he identified as the 74-year-old Antoni Gaudí, architect of the unfinished temple of the Sagrada Familia and a dozen other smaller (but, many believe, better) buildings in and just outside his city.

The Sagrada Familia, or (to give its full name) the Expiatory Temple of the Holy Family, is beyond rival the best-known structure in Catalonia. It is to Barcelona what the Eiffel Tower is to Paris or the Harbour Bridge to Sydney: a completely irreplaceable logo. Being unfinished, it is also much misunderstood, starting with the fact that so many of the millions of tourists who visit it every year imagine that it is a "cathedral". But Barcelona had already had a perfectly fine cathedral since feudal times. The Sagrada Familia was intended to be what its name says: a temple, where Catalans (and, Gaudí hoped, eventually the whole Catholic world) would converge to do penance for the sins of "modernity".

In the last quarter of the 19th century, the Catholic church felt it was under siege from all those forces of atheism, scientism, disobedience and doubt that its hierarchy rolled together into the portmanteau word "modernism". Huge rearguard actions were fought by Rome. There was Pope Pius IX's "Syllabus of Errors", launched against the threat of liberalism and listing just about every conceivable advanced or critical idea about sin, belief and duty as a loathsome heresy, to be punished in hellfire. Extreme dogmas were promulgated, such as that of papal infallibility. It is probably true to say that, in the late-19th century, the Catholic church became more ferocious in its perception of heretical threat than it had been since the time of Luther. And Gaudí, to whom a penitential relationship with an implacable God was the very core of religious belief, was just the architect to convey this in stone.

What the church wanted was a new counter-reformation, based on an extreme ratcheting-up of cultic devotion to Jesus, Mary and the saints. Gaudí conceived his temple as a means to that end. It would be an ecstatically repressive building that would help atone for the "excesses" of democracy. "Everyone has to suffer," he once told a disciple. "The only ones who don't suffer are the dead. He who wants an end to suffering wants to die."

Gaudí was born in 1852 in Reus, a fair-sized provincial town in the lower plains of Tarragona. He came from an artisan family of metalsmiths. The country round Tarragona is archetypally Mediterranean, hard stony country where almond trees and olives flourish in the unforgiving soil. Growing up there, Gaudí developed a passionate curiosity about its plants, animals and geology. Nature, he said later, was "The Great Book, always open, that we should force ourselves to read". Everything structural or ornamental that an architect might imagine was already prefigured in natural form, in limestone grottoes or dry bones, in a beetle's shining wing case or the thrust of an ancient olive trunk.

He never ceased to draw on nature. Each paving-block of Passeig de Gracia features a starfish and an octopus, originally designed for the Casa Batllo. Turtles and tortoises support the columns of the Nativity facade of the Sagrada Familia, which also has 30 different species of stone plant copied from the vege- tation of Catalunya and the Holy Land. Mushrooms become domes, or columns of the Casa Calvet. Gaudí was particularly fond of mushrooms. Most Catalans are, yet Gaudí not only perceived in them a possible origin of the column and capital, but also used a fong, a poisonous amanita mushroom, for one of the ceramic entrance domes of the Parc Güell. The columns of his masterpiece the Güell Crypt are a grove of brick trunks, sending out branches - the ribbed vaults - that lace into one another.

Gaudí never forgot country buildings in stone, clay and timber - materials, he said (with a sovereign disregard for the working hours of common folk) "which can be gathered by the peasants themselves in their spare time between their labours." Thus the rough stone walls of terraces in the Baix Camp became the "rustic" colonnades of the Parc Güell. In the latter years of his life, when making the figures for the Nativity facade of the Sagrada Familia, he made literal transcriptions from nature, by chloroforming birds and even a donkey in order to cast them in plaster. Sometimes this effigy-making was of a rather gruesome kind; in order to make infants for his scene of the Slaughter of the Innocents, he got permission from the Hospital of the Holy Cross on the Ramblas to cast the corpses of stillborn babies in plaster; live ones could not be used since they could not be prevented from moving. There exists an old photo of the inside of one of Gaudí's studios, looking like a charnel-house, with plaster bodies and limbs hanging on every wall. But what mattered most to him were the forms and structural principles that could be deduced from inanimate matter, plants and rock-forms especially.

His artisan ancestry mattered immensely to Gaudí. He thought of himself as a man of his hands, not a theoretician. He said he learned about complex membranes by watching his father beat iron and copper sheets, making up the forms as he went along without drawing them first. Unlike his colleagues Puig i Cadafalch and Domenech i Montaner, he thought in terms of manual, not conceptual space. His mature work can't be imagined at all from flat drawings. Its surfaces twist and wiggle. The space flares, solemnly inflates, then collapses again. He did not like to draw - it didn't give enough information about the complex spaces he carried in his head - and he only used drawing as a last resort. Instead, he made models, from wood, clay or turnips.

Because abstractions bored him, and he did not think naturally in terms of T-square architecture (orthographic projection: plan, elevations, sections), he was not highly esteemed as a student and seems not to have won exceptional grades - not the first time by any means that a genius has not seemed to be one when at school. Also, the teachers at the school were much more interested in transmitting the principles of Graeco-Roman planning and ornament to their pupils than in teaching what most interested Gaudí - rural vernacular building and Catalan medievalism. The lessons of both, he came to believe, fused in a unique sensibility that was nationalist at root, that could only be fully pursued in Catalonia - neither pinched like the Protestant north nor laxly sensuous like the deep Arabic south. "Our strength and superiority lies in the balance of feeling and logic," he wrote, "whereas the Nordic races become obsessive and smother feeling. And those of the south, blinded by the excess of colour, abandon reason and produce monsters."

One medieval complex in particular fired Gaudí's imagination as a teenager. It was the monastery of Santa Maria de Poblet, some way inland from Barcelona, not far from Reus. This once mighty Cistercian foundation had begun in the mid-12th century. Its historical and patriotic import was immense, since from the time of his death all the kings of Aragon and Catalonia had been buried there. It was therefore the national pantheon. As architecture, it was the grandest Cistercian building in Catalonia, strong, severe and plain. But when Gaudí was a boy, Poblet was a ruin and he conceived the mad, devout idea of restoring it to at least a memory of its former glories. To him it was the arch-symbol of Catholic supremacy and Catalan identity - and the liberals had ruined it in the name of "freedom" and "rights".

Thus in Gaudí's mind, religious conservatism - the more extreme, the nobler - fused with the retention of Catalan identity. Hence his obsession with making amends to God. Very luckily for him, he found a patron for his work. He was the magnate Eusebi Güell, fanatical Catholic and quintessential grandee of the Catalan establishment. Practically all Gaudí's first projects were for Güell: the fierce iron dragon gate of his finca [estate], and the weirdly lugubrious Güell Palace off the Ramblas, which has the most beautiful roof in Spain - an acropolis of 20 or more chimneys and ventilators, each sheathed in trencadis or irregular mosaics of broken tile and glass.

He was fascinated by how the mosaic fragmentation of the trencadis played against the solidity of architectural form, dissolving its stability. Later, his brilliant but lesser-known colleague Josep Maria Jujol would design the trencadi patterns for the walls and serpentine seats in the park of a large (but financially unsuccessful) housing project Güell began on Mont Pelat, overlooking the city, which became the Parc Güell.

Güell, as an enlightened capitalist, wanted to reduce friction between workers and management - Barcelona was a city of frequent riots and strikes. He decide d to create an industrial village, or colonia, south of Barcelona. It would have every amenity, including a church, which would naturally be de- signed by Gaudí. He started thinking about the design in 1898. The first stones were laid in 1908. Eusebi Güell died in 1918. By then, the crypt was almost finished, but there was not much above ground. What we have now is only a fragment of a dream. And yet its logic of construction, its sheer blazing inventiveness, removes it from the domain of fantasy and creates one of the world's most sublime architectural spaces.

How did Gaudí do it? Upside down, with string and little bags of birdshot: the infinitely laborious ancestor of computer modelling. Gaudí draws out the plan of the crypt, and marks where each column would meet the floor. He hangs a string from each point, and connects the hanging strings with cross-strings to simulate beams, arches and vaults, attaching to each string a tiny bag of lead pellets, care- fully scaled at so many milligrams per pellet. The result is a web of forces. All the forces in the web would be tensile, since string has zero resistance to bending. Now he photographs the model 72 times, with a five-degree change of rotation each time. And he turns the photos upside down. Tension becomes compression. All the angles of lean in the crypt are plotted. And because there will be no tensile bending stress anywhere in the structure, it can be built of stone, brick and tile by traditional masons - in a technology that hasn't changed since the 14th century.

· Barcelona and Modernity: Gaudí to Dali is at the Metropolitan Museum of Art, New York, from March 7 to June 3