A CMPPreference enables shared preference management in Android and iOS apps using Compose Multiplatform, ensuring seamless cross-platform functionality.
Installation
Add the dependency to your build.gradle.kts file:
commonMain.dependencies {
implementation("network.chaintech:cmp-preference:1.0.0")
}
Usage
- Add the following line in onCreate of your Activity class in Android:
class AppActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
...
AppContext.apply { set(this@AppActivity) }
...
}
}
Example
@Composable
fun App() = AppTheme {
LocalPreferenceProvider {
val preference = LocalPreference.current
var value by remember { mutableStateOf("---") }
var text by remember { mutableStateOf("") }
Column(
modifier = Modifier
.fillMaxSize()
.windowInsetsPadding(WindowInsets.safeDrawing)
.padding(top = 36.dp, start = 16.dp, end = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
TextField(
value = text,
onValueChange = { text = it },
label = { Text("Enter text") },
modifier = Modifier
.fillMaxWidth()
.height(60.dp),
)
Row(
modifier = Modifier
.padding(top = 30.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Button(
modifier = Modifier
.height(54.dp)
.weight(1f),
onClick = {
if (text.isNotEmpty())
preference.put("ENTER_YOUR_KEY", text)
},
colors = ButtonDefaults.buttonColors(Color(0xFF007AFF)),
) {
Text(
"Store value",
style = MaterialTheme.typography.bodyLarge,
fontSize = 17.sp
)
}
Button(
modifier = Modifier
.height(54.dp)
.weight(1f),
onClick = {
value = preference.getString("ENTER_YOUR_KEY") ?: "---"
},
colors = ButtonDefaults.buttonColors(Color(0xFF007AFF)),
) {
Text(
"Get value",
style = MaterialTheme.typography.bodyLarge,
fontSize = 17.sp
)
}
}
Text(
text = "Stored value: $value",
style = MaterialTheme.typography.titleLarge,
textAlign = TextAlign.Center,
fontSize = 20.sp,
modifier = Modifier
.padding(top = 30.dp)
.fillMaxWidth()
)
}
}
}
Screenshot
Conlusion
A CMPPreference enables shared preference management in Android and iOS apps using Compose Multiplatform, ensuring seamless cross-platform functionality. By unifying preference handling, developers can deliver a cohesive user experience and streamline app maintenance across both platforms.
Happy coding ❤
Connect with us 👇
Top comments (0)