且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不重新启动应用程序的情况下更改Flutter应用程序的语言?

更新时间:2022-11-03 14:07:29

将您的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.