Flutter Text重新恢复(在设置状态后)

huangapple go评论120阅读模式
英文:

Flutter Text Reverting Back (after set state)

问题

我基本上在我的应用程序上有一个编辑名称的功能(目前是硬编码的),允许用户更改他们的名称。但是,名称在页面加载之前被获取,所以我在一个未来生成器类型的小部件中执行了这个操作。不幸的是,名称更改本身是有效的,但当我再次回到文本字段并尝试再次更改名称时,名称会恢复到旧的状态。下面是一些屏幕截图,展示了我的意思。

在我尝试更改名称之前:[![Before I tried to change the name][1]][1]

当我更改了名称:[![When I changed the name][2]][2]

恢复为'BOB'![![What I want fixed][3]][3]

以下是我的代码(非常感谢!我已经在这个上面工作了好几天!):

  1. class ProfileInfo extends StatefulWidget {
  2. String? name;
  3. String? email;
  4. ProfileInfo({this.name, this.email});
  5. @override
  6. _ProfileInfoState createState() => _ProfileInfoState();
  7. }
  8. class _ProfileInfoState extends State<ProfileInfo> {
  9. var nameController = TextEditingController();
  10. void updateName(String newName) async {
  11. SharedPreferences prefs = await SharedPreferences.getInstance();
  12. prefs.setString('name', newName);
  13. setState(() {
  14. nameController.text = newName;
  15. widget.name = newName;
  16. });
  17. }
  18. void _showEditNameDialog(BuildContext context) {
  19. // Set the nameController.text to the current name
  20. nameController.text = widget.name ?? '';
  21. showDialog(
  22. context: context,
  23. builder: (BuildContext context) {
  24. return AlertDialog(
  25. title: Text('Edit Name'),
  26. content: TextField(
  27. controller: nameController,
  28. decoration: InputDecoration(hintText: 'Enter your name'),
  29. ),
  30. actions: <Widget>[
  31. TextButton(
  32. onPressed: () {
  33. Navigator.of(context).pop();
  34. },
  35. child: Text('Cancel'),
  36. ),
  37. ElevatedButton(
  38. onPressed: () {
  39. // Save the edited name if needed
  40. updateName(nameController.text);
  41. Navigator.of(context).pop();
  42. },
  43. child: Text('Save'),
  44. ),
  45. ],
  46. );
  47. },
  48. );
  49. }
  50. void redirtohome() async {
  51. var t = await getQuote();
  52. Navigator.of(context).pushReplacement(
  53. MaterialPageRoute(
  54. fullscreenDialog: true,
  55. builder: (context) => home_page(quotes: t),
  56. ),
  57. );
  58. }
  59. @override
  60. Widget build(BuildContext context) {
  61. Size size = MediaQuery.of(context).size;
  62. return Column(
  63. children: [
  64. SizedBox(
  65. width: size.width * .9,
  66. child: Row(
  67. children: [
  68. InkWell(
  69. onTap: Navigator.of(context).pop,
  70. child: Image.asset(
  71. "assets/images/whitebackarrow.png",
  72. width: size.width * .05,
  73. ),
  74. ),
  75. SizedBox(width: 10),
  76. Text(
  77. 'Edit Profile',
  78. style: TextStyle(color: Colors.white, fontSize: 20),
  79. ),
  80. Spacer(),
  81. SizedBox(
  82. width: size.width * .3,
  83. height: size.height * .065,
  84. child: ElevatedButton(
  85. style: ElevatedButton.styleFrom(
  86. shape: RoundedRectangleBorder(
  87. borderRadius: BorderRadius.circular(20),
  88. ),
  89. backgroundColor: Colors.transparent,
  90. shadowColor: Colors.transparent,
  91. ),
  92. onPressed: () {
  93. redirtohome();
  94. },
  95. child: Text(
  96. 'JustLift',
  97. style: TextStyle(
  98. color: Colors.white,
  99. fontSize: 16.0,
  100. fontWeight: FontWeight.bold,
  101. ),
  102. ),
  103. ),
  104. ),
  105. ],
  106. )),
  107. SizedBox(height: 10),
  108. SizedBox(height: 10),
  109. Container(
  110. height: size.height * 0.3,
  111. width: size.width * .9,
  112. child: Stack(
  113. alignment: Alignment.center,
  114. children: <Widget>[
  115. Icon(
  116. Icons.circle,
  117. color: Color(0xff11b779),
  118. size: size.height * 0.3,
  119. ),
  120. Text(
  121. widget.name!.length >= 2
  122. ? widget.name!.substring(0, 2).toUpperCase()
  123. : widget.name!,
  124. style: TextStyle(
  125. fontSize: size.height * 0.13,
  126. color: Colors.white,
  127. fontWeight: FontWeight.bold),
  128. ),
  129. ],
  130. ),
  131. ),
  132. SizedBox(height: 10),
  133. Container(
  134. width: size.width * .9,
  135. height: 30,
  136. color: Colors.grey.withOpacity(.14),
  137. padding: EdgeInsets.only(top: 4, left: 10),
  138. child: Text(
  139. 'NAME',
  140. style: TextStyle(
  141. fontSize: 18,
  142. color: Colors.grey.withOpacity(.8),
  143. fontWeight: FontWeight.bold,
  144. ),
  145. ),
  146. ),
  147. Container(
  148. width: size.width * .9,
  149. child: TextButton(
  150. onPressed: () {
  151. _showEditNameDialog(context);
  152. },
  153. child: Row(children: [
  154. Text(
  155. widget.name!,
  156. style: const TextStyle(
  157. color: Color(0xFFCECECE),
  158. fontSize: 18,
  159. fontWeight: FontWeight.bold,
  160. ),
  161. ),
  162. Spacer(),
  163. Icon(Icons.edit, color: Color(0xFFCECECE)),
  164. ]))),
  165. Container(
  166. width: size.width * .9,
  167. height: 30,
  168. color: Colors.grey.withOpacity(.14),
  169. padding: EdgeInsets.only(top: 4, left: 10),
  170. child: Text(
  171. 'EMAIL',
  172. style: TextStyle(
  173. fontSize: 18,
  174. color: Colors.grey.withOpacity(.8),
  175. fontWeight: FontWeight.bold,
  176. ),
  177. ),
  178. ),
  179. Container(
  180. width: size.width * .9,
  181. padding: EdgeInsets.all(10),
  182. child: Text(
  183. widget.email!,
  184. style: const TextStyle(
  185. color: Color(0xFFCECECE),
  186. fontSize: 18,
  187. fontWeight: FontWeight.bold,
  188. ),
  189. ),
  190. )
  191. ],
  192. );
  193. }
  194. }
  195. class EditProfilePage extends StatefulWidget {
  196. @override
  197. _EditProfilePageState createState() => _EditProfilePageState();
  198. }
  199. class _EditProfilePageState extends State<EditProfilePage> {
  200. String? name = '';
  201. String? email = '';
  202. @override
  203. void initState() {
  204. super.initState();
  205. getInfo();
  206. }
  207. Future<void> getInfo() async {
  208. SharedPreferences prefs = await SharedPreferences.getInstance();
  209. setState(() {
  210. name = prefs.getString('name');
  211. email = prefs.getString('email');
  212. });
  213. }
  214. @override
  215. Widget build(BuildContext context) {
  216. if (name == null || email == null) {
  217. return Center(
  218. child: SizedBox(
  219. height: 50.0,
  220. width: 50.0,
  221. child: CircularProgressIndicator(),
  222. ),
  223. );
  224. } else {
  225. return buildPage(context);
  226. }
  227. }
  228. @override
  229. Widget buildPage(BuildContext context) {
  230. Size size = MediaQuery.of(context).size;
  231. double height = MediaQuery.of(context).viewPadding.top;
  232. return Scaffold
  233. <details>
  234. <summary>英文:</summary>
  235. I basically have an edit name feature on my app, (for now hardcoded), that allows users to change their name. However the name is fetched before the page loads, so I do that in a future builder type widget. Unfortunatly **the name changing itself works, but when I go back into the text field and attempt to change the name again, the name reverts back to its old self. here are some screenshots showing what I mean**
  236. Before I tried to change the name: [![Before I tried to change the name][1]][1]
  237. When I changed the name: [![When I changed the name][2]][2]
  238. REVERTED BACK TO &#39;BOB&#39;![![What I want fixed][3]][3]
  239. Here is my code (THANK YOU SOOO MUCH! I&#39;VE BEEN WORKING ON THIS FOR DAYS!!!!):

class ProfileInfo extends StatefulWidget {
String? name;
String? email;

ProfileInfo({this.name, this.email});

@override
_ProfileInfoState createState() => _ProfileInfoState();
}

class _ProfileInfoState extends State<ProfileInfo> {
var nameController = TextEditingController();

void updateName(String newName) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('name', newName);

  1. setState(() {
  2. nameController.text = newName;
  3. widget.name = newName;
  4. });

}

void _showEditNameDialog(BuildContext context) {
// Set the nameController.text to the current name
nameController.text = widget.name ?? '';

  1. showDialog(
  2. context: context,
  3. builder: (BuildContext context) {
  4. return AlertDialog(
  5. title: Text(&#39;Edit Name&#39;),
  6. content: TextField(
  7. controller: nameController,
  8. decoration: InputDecoration(hintText: &#39;Enter your name&#39;),
  9. ),
  10. actions: &lt;Widget&gt;[
  11. TextButton(
  12. onPressed: () {
  13. Navigator.of(context).pop();
  14. },
  15. child: Text(&#39;Cancel&#39;),
  16. ),
  17. ElevatedButton(
  18. onPressed: () {
  19. // Save the edited name if needed
  20. updateName(nameController.text);
  21. Navigator.of(context).pop();
  22. },
  23. child: Text(&#39;Save&#39;),
  24. ),
  25. ],
  26. );
  27. },
  28. );

}

void redirtohome() async {
var t = await getQuote();
Navigator.of(context).pushReplacement(
MaterialPageRoute(
fullscreenDialog: true,
builder: (context) => home_page(quotes: t),
),
);
}

@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Column(
children: [
SizedBox(
width: size.width * .9,
child: Row(
children: [
InkWell(
onTap: Navigator.of(context).pop,
child: Image.asset(
"assets/images/whitebackarrow.png",
width: size.width * .05,
),
),
SizedBox(width: 10),
Text(
'Edit Profile',
style: TextStyle(color: Colors.white, fontSize: 20),
),
Spacer(),
SizedBox(
width: size.width * .3,
height: size.height * .065,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
backgroundColor: Colors.transparent,
shadowColor: Colors.transparent,
),
onPressed: () {
redirtohome();
},
child: Text(
'JustLift',
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
),
),
],
)),
SizedBox(height: 10),
SizedBox(height: 10),
Container(
height: size.height * 0.3,
width: size.width * .9,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Icon(
Icons.circle,
color: Color(0xff11b779),
size: size.height * 0.3,
),
Text(
widget.name!.length >= 2
? widget.name!.substring(0, 2).toUpperCase()
: widget.name!,
style: TextStyle(
fontSize: size.height * 0.13,
color: Colors.white,
fontWeight: FontWeight.bold),
),
],
),
),
SizedBox(height: 10),
Container(
width: size.width * .9,
height: 30,
color: Colors.grey.withOpacity(.14),
padding: EdgeInsets.only(top: 4, left: 10),
child: Text(
'NAME',
style: TextStyle(
fontSize: 18,
color: Colors.grey.withOpacity(.8),
fontWeight: FontWeight.bold,
),
),
),
Container(
width: size.width * .9,
child: TextButton(
onPressed: () {
_showEditNameDialog(context);
},
child: Row(children: [
Text(
widget.name!,
style: const TextStyle(
color: Color(0xFFCECECE),
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
Spacer(),
Icon(Icons.edit, color: Color(0xFFCECECE)),
]))),
Container(
width: size.width * .9,
height: 30,
color: Colors.grey.withOpacity(.14),
padding: EdgeInsets.only(top: 4, left: 10),
child: Text(
'EMAIL',
style: TextStyle(
fontSize: 18,
color: Colors.grey.withOpacity(.8),
fontWeight: FontWeight.bold,
),
),
),
Container(
width: size.width * .9,
padding: EdgeInsets.all(10),
child: Text(
widget.email!,
style: const TextStyle(
color: Color(0xFFCECECE),
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
)
],
);
}
}

class EditProfilePage extends StatefulWidget {
@override
_EditProfilePageState createState() => _EditProfilePageState();
}

class _EditProfilePageState extends State<EditProfilePage> {
String? name = '';
String? email = '';

@override
void initState() {
super.initState();
getInfo();
}

Future<void> getInfo() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
name = prefs.getString('name');
email = prefs.getString('email');
});
}

@override
Widget build(BuildContext context) {
if (name == null || email == null) {
return Center(
child: SizedBox(
height: 50.0, // or another size
width: 50.0,
child: CircularProgressIndicator(),
),
);
} else {
return buildPage(context);
}
}

@override
Widget buildPage(BuildContext context) {
Size size = MediaQuery.of(context).size;
double height = MediaQuery.of(context).viewPadding.top;
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: AppColors('Default').main2,
body: Column(children: [
SizedBox(height: MediaQuery.of(context).padding.top + 10),
Expanded(
child: ProfileInfo(name: name, email: email),
),
Align(alignment: Alignment.bottomCenter, child: Footer(tab: 'More'))
]));
}
}

  1. [1]: https://i.stack.imgur.com/3NkGW.png
  2. [2]: https://i.stack.imgur.com/HH8Tc.png
  3. [3]: https://i.stack.imgur.com/yi326.png
  4. </details>
  5. # 答案1
  6. **得分**: 2
  7. 你可以在initState()中将widget.name放入TextEditingController中:
  8. ```dart
  9. var nameController = TextEditingController();
  10. @override
  11. void initState() {
  12. super.initState();
  13. nameController.text = widget.name ?? '';
  14. }

然后在Text widget中使用nameController:

  1. Text(nameController.text,)

使用widget.name来初始化nameController,然后使用nameController来实现业务逻辑。

英文:

For now you can put widget.name to TextEditingController in initState()

  1. var nameController = TextEditingController();
  2. @override
  3. void initState() {
  4. super.initState();
  5. nameController.text = widget.name??&#39;&#39;;
  6. }

Then use the nameController in Text widget.

Text(nameController.text,)

Use widget.name to initialize nameController then user nameController to implement business logic.

答案2

得分: 1

  1. var textEditingController = TextEditingController();
  2. @override
  3. void initState() {
  4. super.initState();
  5. textEditingController.text = widget.name??'';
  6. }
英文:
  1. var textEditingController = TextEditingController();
  2. @override
  3. void initState() {
  4. super.initState();
  5. textEditingController.text = widget.name??&#39;&#39;;
  6. }

huangapple
  • 本文由 发表于 2023年6月22日 12:48:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定