We propose a new method to calculate electric dipole moments induced by the strong QCD $theta$-term. The method is based on the gradient flow for gauge fields and is free from renormalization ambiguities. We test our method by computing the nucleon electric dipole moments in pure Yang-Mills theory at several lattice spacings, enabling a first-of-its-kind continuum extrapolation. The method is rather general and can be applied for any quantity computed in a $theta$ vacuum. This first application of the gradient flow has been successful and demonstrates proof-of-principle, thereby providing a novel method to obtain precise results for nucleon and light nuclear electric dipole moments.