问题
I use setState(() {})
for assigning a value to a variable. But it's printing again and again. Why does it react like this? And how can I fix it?
Here is my code:
class Sample extends StatefulWidget {
@override
_SampleState createState() => _SampleState();
}
class _SampleState extends State<Sample> {
String _message;
String _appLink;
Firestore db = Firestore.instance;
@override
Widget build(BuildContext context) {
db.collection('share').document('0').get().then((value) {
var message = value.data['message'];
print(message);
var appLink = value.data['appLink'];
setState(() {
_message = message;
_appLink = appLink;
});
});
return Container(
child: Text('$_message $_appLink'),
);
}
}
Here is my Output:
Here _appLink
value is www.facebook.com
回答1:
The purpose of setState
is to tell the framework that a variable in the state has changed and the widget needs to be rebuilt to reflect that change. So calling setState
calls the build
function again, which in your case recalls your Future
, which calls setState
again, which triggers build
and so on.
To fix this you should call the Future
in initState
, and use a FutureBuilder
to display the data when it's ready.
Example:
class _SampleState extends State<Sample> {
Firestore db = Firestore.instance;
Future databaseFuture;
@override
void initState() {
databaseFuture = db.collection('share').document('0').get()
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: databaseFuture,
builder: (context, snapshot) {
if(!snapshot.hasData) {
return CircularProgressIndicator();
}
var message = snapshot.data.data['message'];
print(message);
var appLink = snapshot.data.data['appLink'];
return Text('$message $appLink');
}
),
}
}
来源:https://stackoverflow.com/questions/62842729/flutter-why-setstate-set-data-again-and-again