我有以下状态完整的小部件。我只需要更改两个变量id
和collectionName
就可以重用它。通常,我会提取一个小部件,但是在这种情况下,我正在修改变量firstName,这不会让我提取该小部件。
class IndividualSignupPage1 extends StatefulWidget {
static final id = 'idIndividualSignupPage1';
final collectionName = 'Individual';
@override
_IndividualSignupPage1State createState() => _IndividualSignupPage1State();
}
class _IndividualSignupPage1State extends State<IndividualSignupPage1> {
String firstName;
DateTime birthDate;
final firestoreObj = Firestore.instance;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: GeneralAppBar(
appBar: AppBar(),
),
body: Container(
child: Column(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[
TextField(
onChanged: (value) {
this.firstName = value;
},
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Expanded(
child: Card(
child: ListTile(
title: Text(
this.birthDate == null
? 'Birthdate'
: '${this.birthDate.year}-${this.birthDate.month}-${this.birthDate.day}',
),
onTap: () {
DatePicker.showDatePicker(
context,
initialDateTime: this.birthDate,
onConfirm: (newDate, listOfIndexes) {
setState(() {
this.birthDate = newDate;
});
},
);
},
),
),
),
],
),
WFullWidthButton(
name: 'Save',
onPressedFunc: () async {
// save all info to firestore db
firestoreObj.collection(widget.collectionName).document('xyz').setData({
'firstName': this.firstName,
'birthDate': this.birthDate,
}, merge: true);
},
),
]),
),
);
}
}
谢谢
答案 0 :(得分:2)
创建IndividualSignupPage1构造函数,并使用构造函数参数传递数据。
class IndividualSignupPage1 extends StatefulWidget {
final String id;
final String collectionName;
IndividualSignupPage1(this.id,this.collectionName);
答案 1 :(得分:2)
您可以将参数传递给类PersonalSignupPage1,然后在其对应的状态类_IndividualSignupPage1State中使用属性“ widget”。喜欢,
// pass the arguments from another class.
class IndividualSignupPage1 extends StatefulWidget {
final String id;
final String collectionName;
IndividualSignupPage1(this.id,this.collectionName);
@override
_IndividualSignupPage1State createState() => _IndividualSignupPage1State();
}
假设您要在其对应的状态类_IndividualSignupPage1State中使用id和collectionName,则可以使用“ widget” 属性之类的
来访问它appBar: AppBar(title: Text(widget.id)),
**OR**
appBar: AppBar(title: Text(widget.collectionName)),
注意:您只能在函数/方法内访问 widget 属性。