move null check before flatten