Riy*_*oua 3 events onchange textfield dart flutter
我正在遵循这个使用有状态小部件的示例,但我无法使其正常运行,从 onChanged 事件中获取值与 print 函数一起使用,但是当我尝试将值传递给 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')
],
)),
);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
注意:以防万一您在使用 StatelessWidget 时遇到问题。对于 StatefulWidget,您可以在 State 的构建方法之外声明变量,但是当您使用 StatelessWidget 时,您需要全局声明它,如下所示:
import 'package:flutter/material.dart';
String name = ""; //variable declared globally
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 StatelessWidget {
@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')
],
)),
);
}
}
Run Code Online (Sandbox Code Playgroud)
大多数时候,我们使用 BLoC 或提供程序包来管理状态,它们会重新创建 StatelessWidget,而不是更新 StatefulWidget 的状态,这会占用更多内存。
| 归档时间: |
|
| 查看次数: |
3309 次 |
| 最近记录: |