DEV Community

Cover image for Flutter Constants Best Practices 💫 🌌 ✨
Gülsen Keskin
Gülsen Keskin

Posted on • Edited on

7 5

Flutter Constants Best Practices 💫 🌌 ✨

Flutter da tüm constant'ları bir dosyada tutmanın en iyi yolu nedir?

Java ve C#'da her tanım bir sınıfın içinde olmalıdır, bu nedenle yalnızca statik üyelerin var olduğu sınıflar yaygın olarak kullanılır.

Dart'ın üst düzey işlevleri, değişkenleri ve sabitleri vardır, bu nedenle yalnızca bir şeyi tanımlamak için bir sınıfa ihtiyacınız yoktur. İstediğiniz bir namespace ise kitaplık(library) daha uygundur. Kitaplıklar içe aktarma öneklerini ve birleştiricileri show/hide destekler. Bunlar, kodunuzun tüketicisinin ad çakışmalarını kendileri için en iyi şekilde işlemesini sağlayan güçlü araçlardır.

Bir fonksiyon veya değişken mantıksal olarak bir sınıfa bağlı değilse, onu en üst düzeye koyun. Ad çakışmalarından endişe ediyorsanız, ona daha kesin bir ad verin veya önekle import edilebilen ayrı bir library'e taşıyın.

Doğru kullanım:

DateTime mostRecent(List<DateTime> dates) {
  return dates.reduce((a, b) => a.isAfter(b) ? a : b);
}

const _favoriteMammal = 'weasel';
Enter fullscreen mode Exit fullscreen mode

Yanlış kullanım:

class DateUtils {
  static DateTime mostRecent(List<DateTime> dates) {
    return dates.reduce((a, b) => a.isAfter(b) ? a : b);
  }
}

class _Favorites {
  static const mammal = 'weasel';
}
Enter fullscreen mode Exit fullscreen mode

Örnek Uygulama:

constants.dart adında yeni bir dosya oluşturun.

Aşağıda görüldüğü gibi constantlarınızı bildirin.

 const succesMessage=" İşlem başarılı.";

 // Api related 
 const apiBaseURL = "https://baseurl.com";

 const userLoginApi = "login";
 const userSignupApi = "signup";

 // Shared Preference keys 
 const kDeviceName = "device_name";
 const kDeviceUDID = "device_id";

 // Asset Constants
 const navBarLogoImage = "assets/images/home_images/sample.png"
Enter fullscreen mode Exit fullscreen mode

Stil kurallarında belirtildiği gibi constantlarınızı isimlendirirken lowerCamelCase biçimlendirmesini kullandığınızdan emin olun. bkz: navBarLogoImage

Ardından, sabitlere erişmesi gereken herhangi bir dart dosyasının en üstüne aşağıdaki import ifadesini ekleyin:

import 'constants.dart' as constants;

constants.dart dosyanız farklı bir dizindeyse , import ifadenizde constants.dart yolunu belirtmeniz gerektiğini unutmayın.

Absolute path örneği:

import 'package:<your_app_name>/common/constants.dart' as constants;

Artık bu sözdizimi ile sabitlerinize kolayca erişebilirsiniz:

String a = constants.succesMessage;

References:
https://dart.dev/guides/language/effective-dart/design
https://dart.dev/guides/language/effective-dart/style
https://stackoverflow.com/questions/54069239/whats-the-best-practice-to-keep-all-the-constants-in-flutter
https://flutteragency.com/keep-all-the-constants-in-flutter/#:~:text=The%20preferred%20solution%20is%20to,new%20dart%20file%20named%20Constants.

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay