我有两个小部件:Home
和 EntryList
。在 Home
小部件中,我可以更改始终传递到 date
的值 EntryList
,然后应该更新它的 Stream
小部件。
但是,当我更改 Date
值时,EntryList
小部件仍然显示从初始日期而不是这个新日期开始的项目
Home
class HomePage extends StatefulWidget {
const HomePage();
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
DateTime date = new DateTime.now();
void changeDate(int num) {
var newDate =
new DateTime(this.date.year, this.date.month, this.date.day + num);
setState(() {
date = newDate;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
// Change Date and display Date here
Row(
children: [
ElevatedButton(
onPressed: () {
changeDate(-1);
}),
Text(date.toString()),
ElevatedButton(
onPressed: () {
changeDate(1);
}),
]
),
// Our main child component EntryList and passing in date
Row(children: [EntryList(this.date)]),
]
)
)
}
}
EntryList
class EntryList extends StatefulWidget {
final DateTime date;
const EntryList(this.date);
@override
_EntryListState createState() => _EntryListState();
}
class _EntryListState extends State<EntriesList> {
Stream<QuerySnapshot> _entryStream; // my stream
void getEntries(snapshot) {
// code to get items - this works just fine
}
@override
// This is where we use the props in this widget. Not updating after changing parent date value
void initState() {
_entryStream = FirebaseFirestore.instance
.collection(widget.date)
.snapshots();
super.initState();
}
Widget build(BuildContext context) {
return (StreamBuilder(
stream: _entryStream,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
return new ListView(
children: getEntries(snapshot),
);,
},
));
}
}
谁能告诉我为什么不更新?我认为这可能与使用 void dispose
有关,但我不确定如何在这种情况下使用它。
相关(但不是我的解决方案)链接: How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?
答案 0 :(得分:0)
我发现了一个名为 didUpdateWidget
的函数,它允许我在父值更改时更新我的小部件。
以下是对我有帮助的答案:Flutter: re-render child widget on parent state change
@override
void didUpdateWidget(old) {
super.didUpdateWidget(old);
String dateString =
'${widget.date.month}-${widget.date.day}-${widget.date.year}';
_entryStream = FirebaseFirestore.instance
.collection('users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection(dateString)
.snapshots();
}
现在我的子小部件在日期更改后正确显示新数据。