Ultrasensitive real-time detection of trace Pb2+ in continuous flow is vital to effectively and timely eliminate the potential hazards to ecosystem health and sustainability. This work reports on a micro-structured smart hydrogel grating with ultra-sensitivity, high selectivity, good transparency and mechanical property for real-time detection of Pb2+ in continuous flow. The hydrogel grating possesses uniform surface relief microstructures with periodic nano-height ridges made of poly(acrylamide-co-benzo-18-crown-6-acrylamide) networks that crosslinked by tetra-arm star poly(ethylene glycol)acrylamide. The hydrogel grating with good optical transparency and mechanical property can change its height via selective host-guest complexation with Pb2+ to output a changed diffraction efficiency. Meanwhile, the periodic nano-ridges with large specific area benefit the contact with Pb2+ for fast Pb2+-induced height change. Thus, with such rationally designed molecular structures and surface relief microstructures, the hydrogel grating integrated in a glass-based mini-chip allows real-time detection of Pb2+ in continuous flow with ultra-sensitivity and high selectivity. The hydrogel grating detector can achieve ultralow detection limit (10-9 M Pb2+), fast response (2min), and selective detection of Pb2+ from dozens of interfering ions even with high concentrations. This high-performance hydrogel grating detector is general and can be extended to detect many analytes due to the wide choice of responsive hydrogels, thus opening new areas for creating advanced smart detectors in analytical science.