Flutter - Как изменить язык дочерних виджетов - PullRequest
0 голосов
/ 24 февраля 2020

Я хотел бы изменить язык всех приложений без перезагрузки приложения. Я использовал flutter_i18n

У меня есть кнопка переключения языка на appBar и AppHomeScreen в теле, здесь есть build функция в MyHomePage классе:

  addClickFn(model) {
    FocusScope.of(context).requestFocus(FocusNode());
    Navigator.push<dynamic>(
      context,
      MaterialPageRoute<dynamic>(
          builder: (BuildContext context) => MyPopupScreen(callback: (c, id) => { }),
          fullscreenDialog: true),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<ResponseDataModel>(
        builder: (context, _, model) => Scaffold(
              backgroundColor: AppTheme.white,
              body: FutureBuilder<bool>(
                future: getData(),
                builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
                  if (!snapshot.hasData) {
                    return const SizedBox();
                  } else {
                    return Padding(
                      padding: EdgeInsets.only(
                          top: MediaQuery.of(context).padding.top),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          appBar(),
                          Expanded(
                            child: FutureBuilder<bool>(
                              future: getData(),
                              builder: (BuildContext context,
                                  AsyncSnapshot<bool> snapshot) {
                                if (!snapshot.hasData) {
                                  return const SizedBox();
                                } else {
                                  return AppHomeScreen(
                                      addClickFn: () => addClickFn(model));
                                }
                              },
                            ),
                          ),
                        ],
                      ),
                    );
                  }
                },
              ),
            ));
  }

appBar с функцией кнопки переключения onTap:

  Widget appBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 8, left: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
            ),
          ),
          Expanded(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 4),
                child: Text(
                  FlutterI18n.translate(context, "title"),
                  style: TextStyle(
                    fontSize: 22,
                    color: AppTheme.darkText,
                    fontWeight: FontWeight.w700,
                  ),
                ),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 8, right: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
              color: Colors.white,
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius:
                      BorderRadius.circular(AppBar().preferredSize.height),
                  child: Image.asset(
                      'icons/flags/png/' + currentLang.languageCode + '.png',
                      package: 'country_icons'),
                  onTap: () async {
                    setState(() {
                      currentLang = currentLang.languageCode == 'vn'
                          ? new Locale('gb')
                          : new Locale('vn');
                    });
                    await FlutterI18n.refresh(context, currentLang);
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

В AppHomePage Я включил BottomBarView с DashboardScreen в качестве тела вкладки

  @override
  Widget build(BuildContext context) {
    return Container(
      color: AppTheme.background,
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: FutureBuilder<bool>(
          future: getData(),
          builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
            if (!snapshot.hasData) {
              return const SizedBox();
            } else {
              return Stack(
                children: <Widget>[
                  tabBody,
                  bottomBar(),
                ],
              );
            }
          },
        ),
      ),
    );
  }

  Future<bool> getData() async {
    await Future<dynamic>.delayed(const Duration(milliseconds: 200));
    return true;
  }

  Widget bottomBar() {
    return Column(
      children: <Widget>[
        const Expanded(
          child: SizedBox(),
        ),
        BottomBarView(
          tabIconsList: tabIconsList,
          addClick: () {
            if (widget.addClickFn != null) widget.addClickFn();
          },
          changeIndex: (int index) {
            if (index == 0) {
              animationController.reverse().then<dynamic>((data) {
                if (!mounted) {
                  return;
                }
                setState(() {
                  tabBody =
                      DashboardScreen(animationController: animationController);
                });
              });
            }
          },
        ),
      ],
    );
  }

И в DashboardScreen Я показываю метку:

  @override
  Widget build(BuildContext context) {
    return Container(
      color: AppTheme.background,
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: Stack(
          children: <Widget>[
            getMainListViewUI(),
            // getAppBarUI(),
            SizedBox(
              height: MediaQuery.of(context).padding.bottom,
            )
          ],
        ),
      ),
    );
  }

  Widget getMainListViewUI() {
    return ListView(
      scrollDirection: Axis.vertical,
      semanticChildCount: 10,
      children: <Widget>[
        Container(
            padding:
                EdgeInsets.only(top: 0.0, left: 24, right: 24, bottom: 24.0),
            child: Text(FlutterI18n.translate(context, "label.welcome"),
                textAlign: TextAlign.left,
                style: TextStyle(
                  fontFamily: AppTheme.fontName,
                  fontWeight: FontWeight.w700,
                  fontSize: 30 + 6 - 6 * topBarOpacity,
                  letterSpacing: 1.2,
                  color: AppTheme.darkerText,
                ))),
      ],
    );
  }

Когда я нажимаю кнопку переключения языка, весь текст в текущем контексте (название) переводится очень хорошо, но в DashboardScreen (label.welcome)

И когда я нажимаю добавить кнопку на bottomBar, чтобы перенаправить на MyPopupScreen, а затем закрыть это всплывающее окно, текст в DashboardScreen был переведен.

Как Могу ли я изменить весь текст в DashboardScreen, если нажать кнопку переключения языка на MyHomePage?

Извините за мой плохой английский sh !!!

1 Ответ

0 голосов
/ 24 февраля 2020

Вы звоните FlutterI18n.refresh со старым значением currentLang.

Попробуйте:

                    setState(() {
                      currentLang = currentLang.languageCode == 'vn'
                          ? new Locale('gb')
                          : new Locale('vn');

                      FlutterI18n.refresh(context, currentLang);
                    });
...