Junior — Middle
Can you explain the principle of avoiding code repetition in software development?
sobes.tech AI
Answer from AI
The principle of avoiding code repetition (DRY — Don't Repeat Yourself) is about not duplicating the same code in different parts of the program. In Flutter, this is achieved by creating reusable widgets, functions, and methods. For example, if you have a button with the same style in multiple places, it's better to create a separate button widget and use it instead of copying the button code each time.
Example:
class CustomButton extends StatelessWidget {
final String label;
final VoidCallback onPressed;
CustomButton({required this.label, required this.onPressed});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text(label),
style: ElevatedButton.styleFrom(
primary: Colors.blue,
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
),
);
}
}
This approach simplifies code maintenance and development, reduces the likelihood of errors, and improves readability.