Question: How can we assign a theme in Magento 2.1 to a store using setup scripts?

Thank you

Answer: 
Above solutions work but have one shortcoming.
They assume that magento has already registered the theme, before setup script execution.
This is not always the case. If you revert entries in `setup_module` table, you discover that error is "magically fixed".

To avoid it, make sure that themes are registered before setup script execution.
One way to do it is 

```
\Magento\Theme\Model\Theme\Registration::register()

```
Better to use `\Magento\Framework\View\Design\Theme\ListInterface` instead of `\Magento\Theme\Model\ResourceModel\Theme\CollectionFactory`. **ListInterface** have method **getThemeByFullPath**, so your code would be:

```
<?php
namespace Vendor\Module\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\Store;

/**
 * Class InstallData
 */
class InstallData implements InstallDataInterface
{
    const THEME_FULL_PATH = 'frontend/Vendor/theme';

    /**
     * @var \Magento\Theme\Model\Config
     */
    private $config;

    /**
     * @var \Magento\Framework\View\Design\Theme\ListInterface $themeList
     */
    private $themeList;

    /**
     * InstallData constructor.
     *
     * @param \Magento\Framework\View\Design\Theme\ListInterface $themeList
     * @param \Magento\Theme\Model\Config $config
     */
    public function __construct(
        \Magento\Framework\View\Design\Theme\ListInterface $themeList,
        \Magento\Theme\Model\Config $config
    ) {
        $this->themeList = $themeList;
        $this->config = $config;
    }

    /**
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        $this->assignTheme();

        $setup->endSetup();
    }

    /**
     * Assign Theme
     *
     * @return void
     */
    protected function assignTheme()
    {
        /** @var \Magento\Framework\View\Design\ThemeInterface $theme */
        $theme = $this->themeList->getThemeByFullPath(self::THEME_FULL_PATH);

        if ($theme->getId()) {
            $this->config->assignToStore($theme, [Store::DEFAULT_STORE_ID], ScopeConfigInterface::SCOPE_TYPE_DEFAULT);
        }
    }
}

```

And you should add di.xml to your module

```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Vendor\Module\Setup\InstallData">
        <arguments>
            <argument name="themeList" xsi:type="object">Magento\Theme\Model\ResourceModel\Theme\Collection</argument>
        </arguments>
    </type>
</config> 

```