setState called during build
One way to avoid this error is to use the Navigator API to trigger the dialog as a route.
body: Center( child: ElevatedBut ton( child: Text ('Launch screen') onPressed: () { // Navigate to the second screen using a named route. Navigator.pushNamed (context, '/second'); // Immediately show a dialog upon loading the second screen. Navigator.push( context, PageRouteBuilder ( barrierDismissible : true, opaque: false, pageBuilder: (_, anim1, anim2) => MyDialog(), ), ); } ) )