我试图通过访问状态类的方法来查看另一个类的文本字段数据。单击按钮时,我想在另一个类中获取文本字段值。
我尝试调用应该返回字符串的方法,但是当我尝试从另一个类访问它时却没有任何值。
class TitleWidget extends StatefulWidget{
final IncidentComponent data;
String titleVal;
TitleWidget(this.data);
@override
TitleWidgetState createState() => TitleWidgetState();
}
class TitleWidgetState extends State<TitleWidget>{
final titleController = TextEditingController();
titleTextValue() {
print("title text field: ${titleController.text}");
return titleController.text;
}
@override
void initState() {
super.initState();
titleController.addListener(titleTextValue);
}
@override
Widget build(BuildContext context) {
return TextField(
controller: titleController);
}
}
我试图访问上述方法以在另一个类中获取字符串。
FloatingActionButton.extended(
label: Text("Complete Report",
onPressed: () { print('title is ' + TitleWidgetState().titleTextValue()); }
)
当我按下另一个班级的FAB按钮时,我一直期望文本字段值。但是我从其他类方法中什么也没得到。 但是titleTextValue()方法的print语句将打印正确的文本字段值。
答案 0 :(得分:1)
尝试此全球商店。通过各种物体可以节省大量的工作。最终,您需要掌握集团。
import 'package:flutter_web/material.dart';
import 'package:flutter_web/widgets.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
body: new Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
new MyStatefulWidget1(),
new MyStatefulWidget2(),
],
),
),
);
}
}
class MyStatefulWidget1 extends StatefulWidget {
State createState() => new MyStatefulWidget1State();
}
class MyStatefulWidget1State extends State<MyStatefulWidget1> {
final titleController = TextEditingController();
titleTextValue() {
print("title text field: ${titleController.text}");
return titleController.text;
}
@override
Widget build(BuildContext context) {
store.set("titleTextValue", titleTextValue);
return TextField(controller: titleController);
}
}
class MyStatefulWidget2 extends StatefulWidget {
State createState() => new MyStatefulWidget2State();
}
class MyStatefulWidget2State extends State<MyStatefulWidget2> {
String _text = 'PRESS ME';
@override
Widget build(BuildContext context) {
var titleTextValue = store.get("titleTextValue");
return new Center(
child: new RaisedButton(
child: new Text(_text),
onPressed: () {
print('title is ' + titleTextValue());
}),
);
}
}
class GlobalState {
final Map<dynamic, dynamic> _data = <dynamic, dynamic>{};
static GlobalState instance = GlobalState._();
GlobalState._();
set(dynamic key, dynamic value) => _data[key] = value;
get(dynamic key) => _data[key];
}
final GlobalState store = GlobalState.instance;