How to change a Flutter app language without restarting the app?

后端 未结 4 1245
忘掉有多难
忘掉有多难 2020-12-31 21:15

In the settings page of my app, I would like to add an option that controls the app language.

I can set the language before starting the app like this:



        
4条回答
  •  醉梦人生
    2020-12-31 21:40

    Wrap your MaterialApp into a StreamBuilder which will be responsible for providing the Locale value to your application. And it will enable you to dynamically change it without restarting your app. This is an example using the rxdart package to implement the stream:

      @override
      Widget build(BuildContext context) {
        return StreamBuilder(
          stream: setLocale,
          initialData: Locale('ar',''),
          builder: (context, localeSnapshot) {
            return MaterialApp(
              // other arguments
              locale: localeSnapshot.data,
            );
          }
        );
      }
    
      Stream setLocale(int choice) {
    
        var localeSubject = BehaviorSubject() ;
    
        choice == 0 ? localeSubject.sink.add( Locale('ar','') ) : localeSubject.sink.add( Locale('en','') ) ;
    
    
        return localeSubject.stream.distinct() ;
    
      }
    

    The above demonstration is just a basic way of how to achieve what you want to, but for a proper implementation of streams in your app you should consider using app-wide BloCs, which will significantly improve the quality of your app by reducing the number of unnecessary builds.

提交回复
热议问题