Flutter 重建父小部件
Posted
技术标签:
【中文标题】Flutter 重建父小部件【英文标题】:Flutter rebuild parent widget 【发布时间】:2020-07-25 13:03:49 【问题描述】:我需要帮助。我在 LanguageDropdown 类中有一个下拉小部件,用户可以在其中选择语言。该小部件位于设置类中的设置页面小部件内。其他页面上的语言会更改,但当前页面不会更改。我怎样才能重建那个特定的页面,所以这个页面的语言也会改变? 请看下面的代码
import 'package:jptapp/features/settings/change_language/app_localization.dart';
class LanguageDropDown extends StatefulWidget
@override
_LanguageDropDownState createState()
return _LanguageDropDownState();
class _LanguageDropDownState extends State<LanguageDropDown>
String _value = allTranslations.currentLanguage;
@override
Widget build(BuildContext context)
return DropdownButton<String>(
items: [
DropdownMenuItem<String>(
child: Text('English'),
value: 'en',
),
DropdownMenuItem<String>(
child: Text('Magyar'),
value: 'hu',
),
DropdownMenuItem<String>(
child: Text('Srpski'),
value: 'rs',
),
],
onChanged: (String value)
setState(() async
_value = value;
await allTranslations.setNewLanguage(_value);
);
,
hint: Text(_value),
value: _value,
);
import 'package:jptapp/core/constants/colors.dart';
import 'package:jptapp/features/settings/change_language/app_localization.dart';
import 'package:jptapp/features/settings/widgets/widgets.dart';
class Settings extends StatefulWidget
@override
_SettingsState createState() => _SettingsState();
class _SettingsState extends State<Settings>
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: MyColors.appBarColor,
title: Text(
allTranslations.text('settings'),
),
),
body: ListView(
children: ListTile.divideTiles(
context: context,
tiles: [
ListTile(
trailing: ThemeChangerAnimationButton(),
title: Text(
allTranslations.text('darkmode'),
),
),
ListTile(
trailing: LanguageDropDown(),
title: Text(
allTranslations.text('language'),
),
),
],
).toList(),
),
);
【问题讨论】:
【参考方案1】:我不确定这是否可行,但试试这个:
import 'package:flutter/material.dart';
import 'package:jptapp/features/settings/change_language/app_localization.dart';
class LanguageDropDown extends StatefulWidget
@override
_LanguageDropDownState createState()
return _LanguageDropDownState();
class _LanguageDropDownState extends State<LanguageDropDown>
String _value = allTranslations.currentLanguage;
@override
Widget build(BuildContext context)
return DropdownButton<String>(
items: [
DropdownMenuItem<String>(
child: Text('English'),
value: 'en',
),
DropdownMenuItem<String>(
child: Text('Magyar'),
value: 'hu',
),
DropdownMenuItem<String>(
child: Text('Srpski'),
value: 'rs',
),
],
onChanged: (String value)
setState(() async
_value = value;
await allTranslations.setNewLanguage(_value);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Settings()
));
);
,
hint: Text(_value),
value: _value,
);
【讨论】:
以上是关于Flutter 重建父小部件的主要内容,如果未能解决你的问题,请参考以下文章
Flutter:在 Navigation.pop 上刷新父小部件
如何布局 GridView.count 以便小部件从 Flutter 中的父小部件顶部开始构建?