如何在不重新启动应用程序的情况下更改Flutter应用程序的语言? [英] How to change a Flutter app language without restarting the app?

查看:161
本文介绍了如何在不重新启动应用程序的情况下更改Flutter应用程序的语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序的设置页面中,我想添加一个控制应用程序语言的选项.

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:

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // other arguments
      locale: Locale('ar'),
    );
  }

但是可以在不重新启动应用程序的情况下更改语言吗?

But is it possible to change the language without restarting the app?

推荐答案

将您的MaterialApp包装为StreamBuilder,它将负责为您的应用程序提供Locale值.而且它将使您能够动态更改它,而无需重新启动应用程序.这是使用 rxdart包实施流的示例:

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<Locale> setLocale(int choice) {

    var localeSubject = BehaviorSubject<Locale>() ;

    choice == 0 ? localeSubject.sink.add( Locale('ar','') ) : localeSubject.sink.add( Locale('en','') ) ;


    return localeSubject.stream.distinct() ;

  }

以上演示只是实现所需目标的基本方法,但是为了在应用中正确实现流,您应该考虑使用应用范围的BloC,这将通过降低应用质量来显着提高应用质量不必要的构建数量.

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.

这篇关于如何在不重新启动应用程序的情况下更改Flutter应用程序的语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆