Write? Yes. Speak For? No.
Can you write characters of other races/genders/etc.? Sure. But I think where it gets tricky is can you speak for them, which is another issue.
When writing characters I think of it in terms of a realist painter or an abstract painter -- either I’m drawing something as true to life/form as I can, based on careful observation and study; or I’m manifesting my own emotions / consciousness onto the page and giving it life. If your character is meant to be the former, then it’s probably alright to try and diversify them so long as you remain neutral and aware of your own lens. But if your character is meant to express your own self/psyche, then I would stick to a character that falls more closely to your own background.
The safest bet when writing a character of another gender/race/etc is probably to just ask for feedback from honest proofreaders of that particular group. When they read your character, is it too flat/stereotypical? Is it a valid portrait or a false copy? I’ve sat in several book discussion groups and heard the words, “Did any [insert demographic] even read this crap before they printed it?” too many times. It’s a simple fix that can force you to be a better writer and take a more critical look at your own innate biases before you immortalize them on paper.
Case in point: One of my close book club friends loves horror but can't stand Stephen King, because his minority/female characters often fall flat (and/or dead). Whereas I prefer Dean Koontz - sure, half his books might boil down to a boy and his dog fighting monsters, but the man definitely knows how to write about a boy and his dog.
Writing is more powerful when you write what you know.