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

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

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]

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

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);

    setState(() {
      nameController.text = newName;
      widget.name = newName;
    });
  }

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

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Edit Name'),
          content: TextField(
            controller: nameController,
            decoration: InputDecoration(hintText: 'Enter your name'),
          ),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('Cancel'),
            ),
            ElevatedButton(
              onPressed: () {
                // Save the edited name if needed
                updateName(nameController.text);
                Navigator.of(context).pop();
              },
              child: Text('Save'),
            ),
          ],
        );
      },
    );
  }

  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,
          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

<details>
<summary>英文:</summary>

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**

Before I tried to change the name: [![Before I tried to change the name][1]][1]

When I changed the name: [![When I changed the name][2]][2]

REVERTED BACK TO &#39;BOB&#39;![![What I want fixed][3]][3]

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);

setState(() {
nameController.text = newName;
widget.name = newName;
});

}

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

showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(&#39;Edit Name&#39;),
content: TextField(
controller: nameController,
decoration: InputDecoration(hintText: &#39;Enter your name&#39;),
),
actions: &lt;Widget&gt;[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(&#39;Cancel&#39;),
),
ElevatedButton(
onPressed: () {
// Save the edited name if needed
updateName(nameController.text);
Navigator.of(context).pop();
},
child: Text(&#39;Save&#39;),
),
],
);
},
);

}

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]: https://i.stack.imgur.com/3NkGW.png
[2]: https://i.stack.imgur.com/HH8Tc.png
[3]: https://i.stack.imgur.com/yi326.png
</details>
# 答案1
**得分**: 2
你可以在initState()中将widget.name放入TextEditingController中:
```dart
var nameController = TextEditingController();
@override
void initState() {
super.initState();
nameController.text = widget.name ?? '';
}

然后在Text widget中使用nameController:

Text(nameController.text,)

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

英文:

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

var nameController = TextEditingController();
@override
void initState() {
super.initState();
nameController.text = widget.name??&#39;&#39;;
}

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

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

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:

确定