Beamer List Listings – How to Make \only and lstlisting Work Together

beamercolumnslistings

I have a slide divided in two columns and one of them should include code inside a block that changes in the following slides.
This code works:

\documentclass{beamer}
\usepackage[utf8x]{inputenc}
\usepackage{listings}

\begin{document}
\begin{frame}[fragile]
\frametitle{Title ®}
\centering

\begin{columns}[onlytextwidth]
\begin{column}{0.4\textwidth}
Figure
\end{column}

\begin{column}{0.5\textwidth}
%\only<1>{
    \begin{block}{Block1}
        \begin{lstlisting}
        if(1) {}
        \end{lstlisting}
    \end{block}
%}
%\only<2>{
    \begin{block}{Block2}
        \begin{lstlisting}
        if(2) {}
        \end{lstlisting}
    \end{block}
%}
\end{column}
​\end{columns}

\end{frame}
\end{document}

But when I uncomment

\only<1>{
...
}
\only<2>{
...
}

I get the error:

! Extra }, or forgotten \endgroup.
l.23 }

How can I solve it?

Best Answer

Verbatim material in an argument is problematic. Use the onlyenv environment instead:

\documentclass{beamer}
\usepackage[utf8x]{inputenc}
\usepackage{listings}

\begin{document}
\begin{frame}[fragile]
\frametitle{Title ®}
\centering

\begin{columns}[onlytextwidth]
\begin{column}{0.4\textwidth}
Figure
\end{column}

\begin{column}{0.5\textwidth}
\begin{onlyenv}<1>
    \begin{block}{Block1}
        \begin{lstlisting}
        if(1) {}
        \end{lstlisting}
    \end{block}
\end{onlyenv}
\begin{onlyenv}<2>
    \begin{block}{Block2}
        \begin{lstlisting}
        if(2) {}
        \end{lstlisting}
    \end{block}
\end{onlyenv}
\end{column}
​\end{columns}

\end{frame}
\end{document}

enter image description here