我想获取包含在Widget build()中的值键,但它显示为“未定义”。另外,我需要将此值获取到另一个类。我该如何做?
我试过只取这个值,但它说未定义错误
String newValue = s; // It says Undefined
我也尝试过将这个值传递给另一个类,但是这个方法给出了更多的错误:c
myCard c = myCard();
String classValue = c.s; // It says 'Only static members can be accessed in initializers' and 'The getter 's' isn`t defined for the class 'myCard' '
这是main.dart文件的一部分
class MyCard extends StatefulWidget {
@override
myCard createState() => myCard();
}
class myCard extends State<MyCard> {
int myCount = count - 1;
void click() {
setState(() {
print(titlecard);
Navigator.push(context, MaterialPageRoute(
builder: (context) => setNewText())
);
});
}
@override
Widget build(BuildContext context) {
Key s = Key(myCount.toString()); // I want to get this value
return Center(
key: s,
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: Icon(Icons.album),
title: Text(titlecard[int.parse(s)]),
subtitle: Text(textcard),
),
ButtonTheme.bar( // make buttons use the appropriate styles for cards
child: ButtonBar(
children: <Widget>[
FlatButton(
child: const Text('Change Text'),
onPressed: click,
),
FlatButton(
child: const Text('LISTEN'),
onPressed: () {
print(s);
},
),
],
),
),
],
),
),
);
}
}
class setNewText extends StatefulWidget {
@override
SetNewText createState() => SetNewText();
}
class SetNewText extends State<setNewText> {
myCard c = myCard();
HomePageState s = HomePageState();
String v = c.s; // To here
final titleController = TextEditingController();
final textController = TextEditingController();
final formkey = GlobalKey<FormState>();
List<String> titles = [''];
void _submit() {
setState(() {
if (formkey.currentState.validate()) {
formkey.currentState.save();
Navigator.pop(context);
titlecard.removeAt(count-s.myCount);
titlecard.insert(count-s.myCount, titleController.text);
textcard = textController.text;
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Change Title'),
),
body: Column(
children: <Widget>[
Card(
child: Padding(
padding: EdgeInsets.all(2.0),
child: Form(
key: formkey,
child: Column(
children: <Widget>[
TextFormField(
controller: titleController,
decoration: InputDecoration(
labelText: 'Title'
),
validator: (value) => value.length < 1 ? 'Invalid Title' : null,
onSaved: (value) => value = titleController.text,
),
TextFormField(
controller: textController,
decoration: InputDecoration(
labelText: 'Text'
),
validator: (text) => text.length < 1 ? 'Invalid Text' : null,
onSaved: (text) => text = textController.text,
)
],
),
),
),
),
FlatButton(
textColor: Colors.deepPurple,
child: Text('SUBMIT'),
onPressed: _submit,
),
],
)
);
}
}
1条答案
按热度按时间mhd8tkvw1#
因为你只是在监听值,一种方法是使用流来监听值。你可以初始化类,在那里值可以被流式传输,并在任何地方访问它。请注意,一旦流被关闭,你只能创建一个新的流。
这是一个样本。
在本演示中,
Counter
在_MyHomePageState
中初始化,只能在同一个类中访问。调用counter.setCount(int)
更新流,可以使用StreamBuilder侦听流值以获取快照。