the flies/ gnats shouldnt be able to reach the food. I think you must have something going wrong here. the worms require a beddding ( too poop/and multiply in) this bedding should be partially moist. then there is a layer that you would feed them on top of that. and finally I have a layer of dry bedding on the top. for some people its shredded newspaper, Coco Coir, you name it. this top layer keeps all the flies out. the food is 3 inches or more down, and there is no way the flies can get to it. as well as the top layer is dry so the fungus gnats wont lay eggs in it. always maintain a thick layer of bedding on top of the food, and you should see your fly problem nearly vanish. I still see the occasional fruit fly. but rarely
when i feed, i just peel up the layer of dry bedding on whichever side i didnt feed on last, feed em, and cover them back up with dry bedding. I also keep a thin slice of cardboard on the very top to mark where i fed last and in which direction im feeding in
hope some of that is useful cheers.