What's the best practice to keep all the constants in Flutter?

前端 未结 8 464
终归单人心
终归单人心 2021-01-30 02:11

What\'s the best programming practice to

create a constant class in Flutter

to keep all the application constants for easy referenc

相关标签:
8条回答
  • 2021-01-30 02:49

    Referring to https://dart.dev/guides/language/effective-dart/design

    It's a good practice to group, constants and enum-like types in a class like below:

    One small advantage this has over the most voted answer, is in Android Studio, your can type the class name Color in your code, and Android Studio will be able to suggest auto import of Color class. This is not possible with the most voted answer.

    0 讨论(0)
  • 2021-01-30 02:53

    EDIT

    Now that the flag --dart-define has been added to the different command lines of Flutter, the following answer no-longer applies.

    Instead just declare constants wherever you want, and potentially refer to other answers.


    While there are no technical issues with static const, architecturally you may want to do it differently.

    Flutter tend to not have any global/static variables and use an InheritedWidget.

    Which means you can write:

    class MyConstants extends InheritedWidget {
      static MyConstants of(BuildContext context) => context. dependOnInheritedWidgetOfExactType<MyConstants>();
    
      const MyConstants({Widget child, Key key}): super(key: key, child: child);
    
      final String successMessage = 'Some message';
    
      @override
      bool updateShouldNotify(MyConstants oldWidget) => false;
    }
    

    Then inserted at the root of your app:

    void main() {
      runApp(
        MyConstants(
          child: MyApp(),
        ),
      );
    }
    

    And used as such:

    @override
    Widget build(BuilContext context) {
      return Text(MyConstants.of(context).successMessage);
    }
    

    This has a bit more code than the static const, but offer many advantages:

    • Works with hot-reload
    • Easily testable and mockable
    • Can be replaced with something more dynamic than constants without rewriting the whole app.

    But at the same time it:

    1. Doesn't consume much more memory (the inherited widget is typically created once)
    2. Is performant (Obtaining an InheritedWidget is O(1))
    0 讨论(0)
提交回复
热议问题