首页 > 解决方案 > Flutter FutureBuilder/Stream how to show 2 different widgets in ConnectionState.waiting depending on given time

问题描述

I want to show a Text() widget in the first second of ConnectionState.waiting, but if it takes longer than a second, I want to show a different Widget with a custom Animation.

Simplified code (StatelessWidget):

...
Stream
...
if (snapshot.connectionState == ConnectionState.waiting) {
                    return Text('Loading data');
                    return CustomWidget(); <- Show this widget instead of Text if more than 1 sec
                  }

标签: flutterflutter-futurebuilder

解决方案


I do not know if this is what you need.

First define a DateTime variable:

DateTime time = DateTime.now();

Then in your build method set with the current DateTime:

@override
  Widget build(BuildContext context) {
    time = DateTime.now();

Then in your result you can check the "time" variable with the current DateTime like this:

if (snapshot.connectionState == ConnectionState.waiting) {
  if (DateTime.now().difference(time).inSeconds>10){
    return Text("More than 10 seconds");
  }
  else {
    return Text('Less than 10 seconds');
  }
}

推荐阅读