In this case you actually need to learn harmony (and counterpoint later on), rather than music theory. Think of it this way: Theory is spelling and harmony is grammar. I'd say that composition is creative writing then!
Some general rules that perhaps you can use:
1. When you're working on tonal music (diatonic music), or even modal music, you are bound to be "stuck" in a specific tonal centre. In a... scale. And each scale has its own key signature. A major has 3 sharps (FCG), etc... So depending on where you are and where you're moving, you'll be using the accidentals of the key signatures (scale) you're in.
Keep in mind that exactly because you may be modulating (moving from scale to scale a lot) you won't exactly have all your accidentals in your key signature and be done with it!
2. In case of modulating, you need to remember the sequence of major and minor chords and the relationship of the key signatures: Generally speaking (but not 100%) you don't move from a scale with 3 sharps to one with 5 flats straight away. So chances are that you might mean that the one with 5 flats, is actually spelled with 7 sharps (check the circle of 5ths to understand why (I'm talking about Gb or F#).
3. Further reasons to go from one key signature to the next: The kind of modulation that you're using. If you are in A major chord and make the A into an A# (and then move to B) you're doing a chromatic modulation. etc...
4. Other more light reasons to use a flat or a sharp.
Some chords in my head are pinned down as they are. For me the "primary" (FOR ME) sharps and flats are F#, C#, Ab, Bb, Eb!
Yes there's A#, but A# major chord is spelled with a double sharp, so it's not handy AT ALL! But still, if you're playing around in that area of the diatonic music, then you're bound to use that!
In any other case go for the simplest solution!
5. The remaining reasons have to do about melodic writing rather than harmonic. As Polyphonist once said, if you're going up chromatically you use sharps, if down you use flats.
None of the above "rules" are 100% correct, but they may be helpful...