WordPress change title with custom dynamic

Move the check for the query var into your title filter:

add_filter('pre_get_document_title', 'wpse392764_qv_template_title' );

function wpse392764_qv_template_title( $title ) {
  $foobar = get_query_var( 'foobar' );

  if( empty( $foobar ) )
     return $title;

  return sprintf(
    __( '%s Dynamic - %s', 'wpse392764' ),
    esc_html( $foobar ),
    get_bloginfo( 'name' )
  );
}