A working example based on your code. Be aware that my code scope is limited as I use a layer name without space for everything whereas I should sanitized it in particular for layername
parameter reused in the GPKG. Most of the code logic is based on qgsalgorithmpackage.cpp
C++ code used in Processing algorithm "Package layers" in the answer from @leo-cardona
# Import required if not present
from qgis.PyQt.QtXml import QDomDocument
from qgis.core import (QgsReadWriteContext, QgsProject,
QgsVectorFileWriter, QgsVectorLayer)
def saving_gpkg(styled_layer, out_path):
context = QgsProject.instance().transformContext()
name = styled_layer.name()
options = QgsVectorFileWriter.SaveVectorOptions()
options.layerName = name
options.fileEncoding = styled_layer.dataProvider().encoding()
options.driverName = "GPKG"
QgsVectorFileWriter.writeAsVectorFormatV2(styled_layer, out_path, context, options)
doc = QDomDocument();
readWriteContext = context = QgsReadWriteContext()
styled_layer.exportNamedStyle(doc);
gpkg_layer = QgsVectorLayer(f"{out_path}|layername={name}", name, "ogr")
gpkg_layer.importNamedStyle(doc)
gpkg_layer.saveStyleToDatabase(name, "", True, "")