The dynamics of trait-based metacommunities have attracted much attention, but not much is known about how dispersal and spatial environmental variability mutually interact with each other to drive coexistence patterns and diversity. Here, we present a spatially-explicit model of resource competition in a metacommunity on a one- dimensional environmental gradient. We find that both the strength of dispersal and the range of spatial environmental variability affect coexistence patterns, spatial structure, trait distribution and local and regional diversity. Without dispersal, species are sorted according to their optimal growth conditions on the gradient. With the onset of dispersal source-sink effects are initiated, which increases the effects of environmental filtering and interspecific competition and generates trait lumping, so that only a few species from an environment-defined trait range can survive. Interestingly, for very large dispersal rates the system becomes spatially homogeneous, but nevertheless two species at the extreme ends of the trait-off curve can coexist for large environmental variability. Local species richness follows a classic hump-shaped dependence on dispersal rate, while local and regional diversity exhibit a pronounced peak for intermediate values of the environmental variability. Our findings provide important insights into the factors that shape the structure of trait-based metacommunities.