Last active
June 22, 2023 07:15
-
-
Save oussama-dz/eca3ba199ad58c7c317c51b17824e94a to your computer and use it in GitHub Desktop.
Integrating local storage with the image picker.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Composable | |
| fun ImagePicker() { | |
| var imageUri: Uri? by remember { mutableStateOf(null) } | |
| val context = LocalContext.current | |
| val dataStore = remember { StoreData() } | |
| val scope = rememberCoroutineScope() | |
| val launcher = | |
| rememberLauncherForActivityResult(contract = ActivityResultContracts.OpenDocument()) { | |
| it?.let { uri -> | |
| context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION ) | |
| scope.launch { | |
| dataStore.storeImage(context, uri.toString()) | |
| } | |
| } | |
| } | |
| Column( | |
| modifier = Modifier | |
| .fillMaxSize(), | |
| horizontalAlignment = Alignment.CenterHorizontally, | |
| verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically) | |
| ) { | |
| AsyncImage( | |
| model = imageUri, | |
| contentDescription = null, | |
| modifier = Modifier | |
| .size(200.dp), | |
| contentScale = ContentScale.Crop | |
| ) | |
| Button( | |
| onClick = { | |
| launcher.launch(arrayOf("image/*")) | |
| } | |
| ) { | |
| Text(text = "Pick Image") | |
| } | |
| } | |
| LaunchedEffect(key1 = true) { | |
| dataStore.getImage(context).collect { | |
| if (it != null) | |
| imageUri = Uri.parse(it) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment