https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
compose
  • o

    oday

    12/16/2022, 2:33 PM
    anyone worked with
    ModalBottomSheetLayout
    before? I have another Composable placed inside its
    sheetContent
    , to show as its content, and a primary Composable that will be shown as the rest of the page when I come to test the main page, the Composable sitting inside the
    ModalBottomSheetLayout
    as the primary thing to be shown in the page, and I check for the existence of some string (which also exists in the sheet WHEN it opens), Im getting that there’s 2 instances of that string, it’s reading the contents of the sheet without it having been opened yet
    i
    7 replies · 2 participants
  • o

    Omkar Amberkar

    12/16/2022, 6:12 PM
    How do i save state of motionlayout on orientation change in compose? When transitioning from start to end and changing orientaiton, i want the end orientation to be shown after orientation change, but it defaults back to start. Checking logs i see that the motion layout state current progress was reset to 0.0 (start state) instead of 1.0 (end state)
  • p

    Pablo

    12/16/2022, 7:55 PM
    Which is the architecture recommended by google to develop android applications with Compose? MVVC? MVP? MVC?
    a
    m
    +1
    4 replies · 4 participants
  • z

    zt

    12/17/2022, 3:11 AM
    What is the default value of
    kotlinCompilerExtensionVersion
    ? Is there a way I can set it throughout my entire project?
    m
    1 reply · 2 participants
  • a

    Ashish Gautam

    12/17/2022, 7:33 AM
    Hey composers, like i have one createScreen composable I added this composable to BottomSheetContent, now when i done the opereation inside CreateScreen , i dissmiss the bottom sheet , when i reopen that sheet I found in last statge of CreateScreen, basically i want the initial state of CreateScreen when i reopen
    m
    3 replies · 2 participants
  • c

    CLOVIS

    12/17/2022, 12:34 PM
    Is it correct that
    androidx.compose.material3
    doesn't have date/time pickers yet?
    c
    2 replies · 2 participants
  • a

    abu naser

    12/17/2022, 1:54 PM
    i am facing a weird problem . i am using compose richtext printing .https://github.com/halilozercan/compose-richtext and in my debug build its okey but after releasing to play store its not working . i tried release build with debuggable true still no problem . so am releasing close testing android 5 times a day . and still same problem . i reverse back to my old compose version , no luck . tried current alpha , no luck . 1 . am i doing it right to release closed test for no reason ? is there a proper way to debug release build that reproduce exact apk like google play ? 2 .how can i remove closed test apk from play store ? my version code keep increasing . 3 .whats the problem with my release build ? here is the release error when i see logcat . java.lang.NullPointerException: Attempt to read from field ‘java.lang.String h2.j.a’ on a null object reference in method ‘h2.c h2.i.b(t0.b, h2.j)’ at h2.i.b(SourceFile:1244) at h2.i.b(SourceFile:911) at h2.i.b(SourceFile:911) at h2.i.b(SourceFile:911) at h2.i.b(SourceFile:911) at y6.x$b.k(SourceFile:26) at s9.a.l(Unknown Source:8) at ha.n0.run(Unknown Source:100) at androidx.compose.ui.platform.m0.X(SourceFile:23) at androidx.compose.ui.platform.m0$c.run(SourceFile:3) at android.os.Handler.handleCallback(Handler.java:942) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loopOnce(Looper.java:201) at android.os.Looper.loop(Looper.java:288) at android.app.ActivityThread.main(ActivityThread.java:7894) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:550) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936) Suppressed: ha.l0: [androidx.compose.ui.platform.t1@21ff2d6, j0.e@b1bc957, x1{Cancelling}@2776c44, m0@6e012d] thanks in advance .
    c
    c
    6 replies · 3 participants
  • d

    Davide Giuseppe Farella

    12/17/2022, 4:43 PM
    Hello people, I have one layout which consumes the status bar insets; this layout may or may not have a sibling placed above, which also consumes the same inserts insets. Since they’re siblings, what is the right way to have the insets consumed only by the first one, instead of both? Example in the screen. Now I set the
    statusBarPadding
    to the yellow box, but on the top bar, thus if the yellow box got removed, the top bar will be drawn behind the status bar
    a
    4 replies · 2 participants
  • g

    Gioele Dev

    12/18/2022, 9:29 AM
    I have a strange issue. ViewModel get data from db with a viewModelScope... after update a list in my uiStage model.. is a MutableStateFlow... when i put a brakpoint i see change while without brakpoint ui doesn/t change.
    i
    6 replies · 2 participants
  • v

    v79

    12/18/2022, 10:19 AM
    Kotlin developers: immutable by default!
    val
    rather than
    var
    ! Compose developers: great, now let's wrap everything in
    mutableStateOf
    to make everything mutable again...
    m
    c
    +3
    5 replies · 6 participants
  • k

    KotlinLeaner

    12/18/2022, 12:00 PM
    Hi guys, I am learning to use BOM in my project
    def composeBom = platform "androidx.compose:compose-bom:$compose_bom"
    implementation composeBom
    androidTestImplementation composeBom
    I see in the gradle doc. Use of
    platform
    is used in transitive version. So what the connection of
    platform
    with BOM? Any guidance will be great..
    1 reply · 1 participant
  • z

    zt

    12/18/2022, 9:04 PM
    Is there anyway to generate a m3 color scheme on a device given a single color? I remember seeing a library to do this but I don't recall its name.
    m
    k
    +1
    4 replies · 4 participants
  • x

    xxfast

    12/19/2022, 12:43 AM
    Hi all - trying to make my
    LargeTopAppBar
    collapse when you scroll on the list view - but it doesn't seem to work. full code in the 🧵
    val scrollState = rememberTopAppBarScrollState()
    val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior(state = scrollState)
    
    LargeTopAppBar(
      modifier = Modifier.windowInsetsPadding(WindowInsets.statusBars),
      ..
      scrollBehavior = scrollBehavior
    )
    Screen Recording 2022-12-19 at 11.42.07 am.mov
    j
    6 replies · 2 participants
  • c

    chanjungskim

    12/19/2022, 3:17 AM
    How can I create LazyColumn in LazyColumn? I get
    java.lang.IllegalStateException: Vertically scrollable component was measured with an infinity maximum height constraints, which is disallowed. One of the common reasons is nesting layouts like LazyColumn and Column(Modifier.verticalScroll()). If you want to add a header before the list of items please add a header as a separate item() before the main items() inside the LazyColumn scope. There are could be other reasons for this to happen: your ComposeView was added into a LinearLayout with some weight, you applied Modifier.wrapContentSize(unbounded = true) or wrote a custom layout. Please try to remove the source of infinite constraints in the hierarchy above the scrolling container.
    error
    k
    m
    +1
    16 replies · 4 participants
  • c

    chanjungskim

    12/19/2022, 3:18 AM
    my code is
    @Composable
    fun SupplementSearchScreen(
        onSearch: (String) -> List<Vitamin>,
        updateRecentAddedSupplementList: List<Vitamin>
    ) {
    
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
        ) {
            item{
                 SupplementSearchResultCard(someList)
            }
        }
    }
    
    @Composable
    fun SupplementSearchScreen(list:List<SomeList>){
        ContentCard(
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = "Hello World",
                fontSize = 16.sp,
                color = Color.Black
            )
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
            ) {
                items(list){ resultItem ->
                    SearchResultItem(resultItem)
                }
            }
        }
    }
  • z

    Zaki Shaikh

    12/19/2022, 6:52 AM
    hello everyone, I want to know that to hold composables screens states in viewModel which one do I use
    SharedFlow
    or
    StateFlow
    ? cuurently I am using
    SharedFlow
    .
    m
    h
    6 replies · 3 participants
  • h

    Hasan Nagizade

    12/19/2022, 8:42 AM
    Hello how can I kill viewmodel after navigating to other screen? for example after logging out I want to kill ViewModel of main screen.
    s
    c
    3 replies · 3 participants
  • m

    Mathew xu

    12/19/2022, 2:57 PM
    I need implement animation of lazy column. The every item of lazy column will fast out from the bottom then slow in to the top. It will play the animation when the new item will be added in lazy column, but the existed item will keep still. I try it with animatewith state, but i failed. Does anyone know how to do it. are there some library can do it?. I searched it on GitHub, but failed to find it.
    c
    7 replies · 2 participants
  • c

    czuckie

    12/19/2022, 4:00 PM
    Is it possible to set a height dynamically on a LazyRow based the largest child it will display?
    c
    c
    6 replies · 3 participants
  • o

    Omkar Amberkar

    12/19/2022, 5:01 PM
    I am trying to resize components inside MotionLayout in compose. How do i wrap the size of MotionLayout according to new progress or as the motion layout is in progress?
  • s

    Slackbot

    12/19/2022, 9:09 PM
    This message was deleted.
  • m

    mattinger

    12/19/2022, 9:19 PM
    So, philosophical question here regarding compose navigation and view models. At the start of our flow, we load some data for the possible devices the user is eligible to onboard. These devices would be stored in a shared viewModel that is owned by the activity, and passed down the chain to the navigation destinations. The user may then end up having to select (or have auto selected if there’s one option) which device to onboard. The way i see it there’s two options for this selection: 1. Store the selection in the view model, and have a route like
    start_onboarding
    which reads the view model to get the device info. 2. Pass the selection in the route like
    start_onboarding/111111
    which can get the device info from the view model, but the selected device is in the path. I see option 2 as a little more flexible in that it keeps the viewModel quite a bit lighter and has some possibilities for proper deep linking. But option 1 is more uniform in that all state is stored in the view model instead of being split in two places.
    d
    5 replies · 2 participants
  • x

    xxfast

    12/19/2022, 10:02 PM
    Is there a easy way to change the shape of
    material3.Slider
    ?
    m
    2 replies · 2 participants
  • t

    Travis Griggs

    12/19/2022, 10:54 PM
    Sigh. Trying to re-engage some Compose work, going through a simple tutorial from Kodeco, and now Column requires me to "Opt in for InternalLayoutApi"? Is this real? or a side effect of trying to update ide, gradle, etc, and some mismatched setting somewhere now?
    c
    k
    +2
    6 replies · 5 participants
  • e

    Erlan Amanatov

    12/20/2022, 6:53 AM
    Hi, I'm facing weird behavior of
    mutableInteractionSource's
    pressed state. So simplified version of my composable looks like this
    @Composable
    fun Sbn(
        interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }
    ) {
        val pressed by interactionSource.collectIsPressedAsState()
        val target by rememberUpdatedState(newValue = if (pressed) Color.Red else Color.Green)
        Box(
            modifier = Modifier
                .padding(24.dp)
                .size(64.dp)
                .background(color = target)
                .clickable(
                    interactionSource = interactionSource,
                    indication = null,
                    onClick = {}
                ),
        )
    }
    It works fine, but if I put it in a scrollable column, the pressed state works with some kind of delay. Any workarounds? Video in thread
    c
    c
    +2
    13 replies · 5 participants
  • t

    Tanuj Soni

    12/20/2022, 8:01 AM
    I want to set my cursor position in a TextField at end when i select texts from a List of texts in jetpack compose, I am using a MutableState of String to maintain a state of text inside a textfield as it can have values from different composables, Can anyone please help me
    z
    2 replies · 2 participants
  • e

    Elio Maroun

    12/20/2022, 8:05 AM
    @Composable
    fun DynamicSchedule(
        viewModel: CalenderViewModel,
        modifier: Modifier = Modifier,
        appointmentContent: @Composable (appointment: Appointment) -> Unit = {
            ScheduleCard(
                appointment = it
            )
        },
        minDate: LocalDate,
        maxDate: LocalDate,
        dayWidth: Dp,
        hourHeight: Dp
    ) {
        val numDays = ChronoUnit.DAYS.between(minDate, maxDate).toInt() + 1
        val dividerColor = if (MaterialTheme.colors.isLight) Color.LightGray else Color.DarkGray
        var offsetY by remember { mutableStateOf(0f) }
        Layout(
            content = {
                viewModel.state.value.appointmentList.sortedBy { it.startDate }
    
                    .forEach { appointment ->
                        Box(modifier = Modifier.appointmentData(appointment)) {
                            appointmentContent(appointment)
                        }
                    }
            },
            modifier = modifier
                .drawBehind {
                    repeat(23) {
                        drawLine(
                            dividerColor,
                            start = Offset(0f, (it + 1) * hourHeight.toPx()),
                            end = Offset(size.width, (it + 1) * hourHeight.toPx()),
                            strokeWidth = 1.dp.toPx()
                        )
                    }
                    repeat(numDays - 1) {
                        drawLine(
                            dividerColor,
                            start = Offset((it + 1) * dayWidth.toPx(), 0f),
                            end = Offset((it + 1) * dayWidth.toPx(), size.height),
                            strokeWidth = 1.dp.toPx()
                        )
                    }
                }
                .pointerInput(Unit) {
                    detectTapGestures {
                        val x = it.x.toDp()
                        val y = it.y.toDp()
                        val time = y.value.toInt() / hourHeight.value
                        val date = (x.value.toInt() / dayWidth.value)
                        println("X: $x, Y: $y")
                        println("Day: $date, Time: $time")
    
                    }
    
                }
                .draggable(
                    orientation = Orientation.Vertical,
                    state = rememberDraggableState { delta ->
                        offsetY += delta
                        println("Delta: $offsetY")
    
                    }
                ),
        ) { measurables, constraints ->
            println("i got recomposed ======== ")
            val height = hourHeight.roundToPx() * 24
            val width = dayWidth.roundToPx() * numDays
            val placeablesWithAppointment = measurables.map { measurable ->
                val appointment = measurable.parentData as Appointment
                val appointmentDurationInMinutes =
                    ChronoUnit.MINUTES.between(
                        appointment.startDate.time.toJavaLocalTime(),
                        appointment.endDate.time.toJavaLocalTime()
                    )
    
                val appointmentHeight =
                    ((appointmentDurationInMinutes / 60f) * hourHeight.toPx()).roundToInt()
                val placeable = measurable.measure(
                    constraints.copy(
                        minWidth = dayWidth.roundToPx(),
                        maxWidth = dayWidth.roundToPx(),
                        minHeight = appointmentHeight,
                        maxHeight = appointmentHeight
                    )
                )
                Pair(placeable, appointment)
            }
            layout(width, height) {
                placeablesWithAppointment.forEach { (placeable, appointment) ->
                    //appointment time - midnight
                    val appointmentOffsetMinutes =
                        ChronoUnit.MINUTES.between(
                            LocalTime.MIN,
                            appointment.startDate.time.toJavaLocalTime()
                        )
                    val appointmentY =
                        ((appointmentOffsetMinutes / 60f) * hourHeight.toPx()).roundToInt()
                    val appointmentOffsetDays =
                        ChronoUnit.DAYS.between(
                            minDate,
                            appointment.startDate.date.toJavaLocalDate()
                        ).toInt()
    
                    val appointmentX = appointmentOffsetDays * dayWidth.roundToPx()
                    placeable.place(appointmentX, appointmentY)
    
                }
            }
    
        }
    }
    I have a custom schedule representing a weekview, how may I listen to drag events to change background color of that surface.
    1 reply · 1 participant
  • v

    v79

    12/20/2022, 8:13 AM
    I think I'm at the stage where I would pay for support to help me understand compose/livedata/room/state/flow stuff! Does such a service exist anywhere? A one-to-one discussion?
    s
    7 replies · 2 participants
  • j

    Jasmin Fajkic

    12/20/2022, 9:10 AM
    How to change height of AlertDialog component but still keep content visible? If I set modifier height for example to 150.dp my content is not visible. I want to decrease height because i do not need title in some cases and need to shrink size. Here how it looks like.
    a
    1 reply · 2 participants
  • d

    dazza5000

    12/20/2022, 2:59 PM
    I am having a similar issue as this user, where
    requestFocus()
    only works the first time it is called. Does anyone know how to work around this issue? https://stackoverflow.com/questions/74391260/jetpack-compose-requestfocus-works-only-once
    z
    12 replies · 2 participants
Powered by Linen
Title
d

dazza5000

12/20/2022, 2:59 PM
I am having a similar issue as this user, where
requestFocus()
only works the first time it is called. Does anyone know how to work around this issue? https://stackoverflow.com/questions/74391260/jetpack-compose-requestfocus-works-only-once
I think the issue for me is that the composable is not recomposed if the error message is the same - so requestFocus doesn't get called again
z

Zach Klippenstein (he/him) [MOD]

12/22/2022, 12:37 AM
Which version of compose?
d

dazza5000

12/22/2022, 4:57 PM
'1.3.2'
You can see this behavior here: https://github.com/dazza5000/textfieldaccessibility/tree/requestFocus
z

Zach Klippenstein (he/him) [MOD]

12/22/2022, 6:47 PM
That link seems broken
Can you post your code? Focus doesn’t have anything to do with recomposition inherently, so I’d need to see exactly what you’re doing.
d

dazza5000

12/22/2022, 7:36 PM
sorry, the repo was private - it's now public
its an entire project
I can post the code here
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {

            var error = remember { mutableStateOf("") }
            var isError = remember { mutableStateOf(false) }
            var value = remember { mutableStateOf(TextFieldValue("")) }
            var focusRequester = remember { FocusRequester() }

            MyApplicationTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Column() {
                        OutlinedTextField(
                            value.value,
                            modifier = Modifier.semantics {
                                if (isError.value) liveRegion = LiveRegionMode.Polite
                            }.focusRequester(focusRequester),
                            onValueChange = {
                                            value.value = it
                            },
                            isError = isError.value,
                            supportingText = {
                                if (isError.value) Text(text = error.value) else null
                            })
                        Button({
                            isError.value = !isError.value
                            error.value = if (isError.value) "we got errorz" else ""
                        }) {
                            Text("Button")
                        }
                    }
                }


                    if (isError.value) focusRequester.requestFocus()

            }
        }
    }
}
z

Zach Klippenstein (he/him) [MOD]

12/23/2022, 2:56 AM
It looks like you’re calling requestFocus in the composition directly, which is not good. I think - slack makes code blocks impossible to read on phones 🙄
That should be in a DisposableEffect or a LaunchedEffect keyed off the value
View count: 7