Preventing cavities is not just about good brushing and flossing, diet plays a HUGE role! It isn’t realistic to say that you shouldn’t eat any sugar, but there are definitely better/worse options for your teeth if you have a sugary craving.
Every time we eat something that contains sugar (most foods) the bacteria in our mouth produce acid for about 90 minutes. This is what demineralizes/softens our enamel and causes cavities. There are 2 main factors involved in how “risky” a food is:
How sticky it is (i.e. how long it stays on your teeth): For example dried vs. fresh fruit. I am always amazed when my kids eat dried fruit, I often see it still stuck to their teeth that night. Fresh fruit is always a better choice!
How frequently you eat/drink it throughout the day: If you are eating/drinking something sugary every 90 minutes, your mouth is constantly at a low pH, making it much more likely you will get cavities.