Issue
I have used flutter_offline library to display the offline and online message. The problem is that I want to hide the online message after some time. I can’t figure out a way to remove a container when the status is connected but after some duration.
Below is my code:
body: OfflineBuilder(
connectivityBuilder: (
BuildContext context,
ConnectivityResult connectivity,
Widget child,
) {
final bool connected = connectivity != ConnectivityResult.none;
return SingleChildScrollView(
scrollDirection: Axis.vertical,
padding: const EdgeInsets.all(0.0),
child: Column(
children: [
AnimatedSwitcher(
duration: const Duration(milliseconds: 350),
child: connected
? Container(
color: Colors.lightGreenAccent[400],
height: 25,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'ONLINE',
style: TextStyle(color: Colors.black),
),
],
))
: Container(
color: Colors.red,
height: 25,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'OFFLINE',
style: TextStyle(color: Colors.white),
),
SizedBox(width: 8.0),
SizedBox(
width: 12.0,
height: 12.0,
child: CircularProgressIndicator(
strokeWidth: 2.0,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.white),
),
),
],
),
)),
child,
],
),
);
},
Solution
Make a bool variable on top of your class. when the connection status change, start a delayed timer and use the empty container to make it invisible after some time.
bool _isContainerVisible = true; // in top of your class
body: OfflineBuilder(
connectivityBuilder: (
BuildContext context,
ConnectivityResult connectivity,
Widget child,
) {
final bool connected = connectivity != ConnectivityResult.none;
if(connnected){
Future.delayed(Duration(seconds: 3).then((v){
if(this.mounted)
setState((){
_isContainerVisible = false;
});
});
}
return SingleChildScrollView(
scrollDirection: Axis.vertical,
padding: const EdgeInsets.all(0.0),
child: Column(
children: [
AnimatedSwitcher(
duration: const Duration(milliseconds: 350),
child: connected
? _isContainerVisible ?Container(
color: Colors.lightGreenAccent[400],
height: 25,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'ONLINE',
style: TextStyle(color: Colors.black),
),
],
)):Container()
: Container(
color: Colors.red,
height: 25,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'OFFLINE',
style: TextStyle(color: Colors.white),
),
SizedBox(width: 8.0),
SizedBox(
width: 12.0,
height: 12.0,
child: CircularProgressIndicator(
strokeWidth: 2.0,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.white),
),
),
],
),
)),
child,
],
),
);
},
Answered By – meditat
Answer Checked By – Candace Johnson (FlutterFixes Volunteer)