What is the correct way to eject a APFS dmg from the command line?
Use the following command.

diskutil eject disk2


From the man pages for hdiutil, the following appears:

 detach dev_name [-force]
            detach a disk image and terminate any associated process.
            dev_name is a partial /dev node path (e.g. "disk1").  As of
            Mac OS X 10.4, dev_name can also be a mountpoint.  If Disk
            Arbitration is running, detach will use it to unmount any
            filesystems and detach the image.  If not, detach will attempt
            to unmount any filesystems and detach the image directly
            (using the `eject' ioctl).  If Disk Arbitration is not run-
            ning, it may be necessary to unmount the filesystems with
            umount(8) before detaching the image.  eject is a synonym for
            detach.  In common operation, detach is very similar to
            diskutil(8)'s eject.

            Options:
            -force   ignore open files on mounted volumes, etc.


So the documentation states you may need to unmount filesystems first. I assume this is what the hdiutil detach /Volumes/Untitled command did.

From the man pages for diskutil, the following appears:

 eject device
            Eject a disk.  Media will become offline for the purposes of
            being a data store for file systems or being a member of con-
            structs such as software RAID or direct data.  Additionally,
            removable media will become eligible for safe manual removal;
            automatically-removable media will begin its physical (motor-
            ized) eject sequence.


Here, there is no mention of having to run any other commands first. 


  Note: For the diskutil eject disk2 command to work, the Untitled volume can not be in use.