Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

flutter - Localizations without calling `of(context)` every time

I find the localization procedure using the official Flutter localization plugin cumbersome. To display a localized string I have to call Localization.of(context).myAppTitle - not exactly sleek or easy to glance over in a huge nested Widget tree with lots of localized strings. Not to mention it looks ugly.

Is there a way to make the usage nicer? For example, can I use a global variable or a static class with a Localization instance member to make the access easier? For example declaring a top level Localization variable

// Somewhere in the global scope
Localization l;


// main.dart
class _MyAppState extends State<MyApp>{

    @override
    void initState() {
        super.initState();
        getLocaleSomehow().then((locale){ 
            l = Localization(locale);
            setState((){}); 
        });
    }
}

Then I could simply call

Text(l.myAppTitle)

So in an essence what I'm asking is "what are the dangers and/or disadvantages of not calling Localization.of(context)?"

If I really do need to use the .of(BuildContext) method to access the Localization instance - can I at least store it in my StatefulWidget? I'm thinking something like

class DetailsPage extends StatefulWidget{
    Localization _l;

    @override
    Widget build(BuildContext context) {
        _l = Localization.of(context);

        // ... build widgets ...
    }
}

Or is there any other way to make the localization less cumbersome?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, it is needed. You could work around it, but that is a bad idea.

The reason for this is that Localization.of<T>(context, T) may update over time. A few situations where it does are:

  • The locale changed
  • The LocalizationsDelegate obtained was asynchronously loaded
  • MaterialApp/CupertinoApp got updated with new translations

If you're not properly calling Localization.of inside build as you should, then in those scenarios your UI may fail to properly update.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...