gpt4 book ai didi

events - 为什么我不能将Flutter TextField onChanged事件值传递给Text?

转载 作者:行者123 更新时间:2023-12-03 04:59:27 27 4
gpt4 key购买 nike

我正在遵循使用状态小部件的示例,但我无法使其正常运行,从onChanged事件中获取值可与打印功能一起使用,但是当我尝试将值传递给Text时,它将不会被接受,原因是文本不在事件本身之外吗?但它仍然在statfulwidget中

这是我的代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hello You',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: new HelloYou(),
);
}
}

class HelloYou extends StatefulWidget {
@override
State<StatefulWidget> createState() => _HelloYouState();
}

class _HelloYouState extends State<HelloYou> {
@override
Widget build(BuildContext context) {
String name = "";

return Scaffold(
appBar: AppBar(
title: Text("HelloYou App !"),
backgroundColor: Colors.blueAccent,
),
body: Container(
padding: EdgeInsets.all(15.0),
child: Column(
children: <Widget>[
TextField(
onChanged: (string) {
setState(() {
name = string;
print('my text is :$name');
});
},
),
Text('my name $name')
],
)),
);
}
}

最佳答案

将字符串变量移出构建。当您将其放入构建中时,setState重新运行构建方法,并且字符串变量消失了。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hello You',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: new HelloYou(),
);
}
}

class HelloYou extends StatefulWidget {
@override
State<StatefulWidget> createState() => _HelloYouState();
}

class _HelloYouState extends State<HelloYou> {

String name = "";

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("HelloYou App !"),
backgroundColor: Colors.blueAccent,
),
body: Container(
padding: EdgeInsets.all(15.0),
child: Column(
children: <Widget>[
TextField(
onChanged: (string) {
setState(() {
name = string;
print('my text is :$name');
});
},
),
Text('my name $name')
],
)),
);
}
}

关于events - 为什么我不能将Flutter TextField onChanged事件值传递给Text?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59872834/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com