Flag 7.x-3.x had two separate APIs for programmatically flagging or unflagging an entity: the procedural API, and the object-oriented API.
These have both been replaced on 8.x-4.x with a service, provided by the FlagService class.
Furthermore, unlike the flag_flag() and flag_unflag() API functions which took care of checking user access, the FlagService methods do not check for access. It is up to the caller to ensure the user account has access (or to decide they want to flag regardless of access). The methods do however check the action makes sense in the application logic: they will throw an exception if the flag does not apply to the entity type, or if the entity is already flagged.
7.x
// Procedural API
$account = user_load($uid);
// Flag the node with nid $nid for user $account.
flag('flag', 'flag_name', $nid, $account);
// Unflag the node with nid $nid for user $account.
flag('unflag', 'flag_name', $nid, $account);
// OO API
$flag = flag_get_flag('flag_name');
$account = user_load($uid);
// Flag the node with nid $nid for user $account.
$flag->flag('flag', 'flag_name', $nid, $account);
// Unflag the node with nid $nid for user $account.
$flag->flag('unflag', 'flag_name', $nid, $account);
8.x
$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);
// Check for access.
if (!$flag->hasActionAccess('flag', $account)) {
return;
}
// Flag the entity for user $account.
$flag_service->flag($flag, $entity, $account);
// Unflag the entity for user $account.
$flag_service->unflag($flag, $entity, $account);
The examples above are a bit misleading because they lack the context of the rest of a Drupal 8 module. Again, the expectation is that you would most likely have access to the objects anyway thanks to the shiny new routing system. If you do need to load the flag entity in isolation, however, you can call FlagService's getFlagById() method. This is a convenience method.