'retry http request on button click after TimeOut flutter
I have create this custom Modal Bottom Sheet which showing when Connection time out or No Internet Connection. I have read retry package, that automatically Retry on SocketException or TimeoutException. how do I retry http request just when user tap on try again button?
Custom Bottom Sheet
class CustomModalBottomSheet {
final typeModal;
final Function() onTryAgainTap;
CustomModalBottomSheet({this.onTryAgain, this.typeModal});
final String connectionTimeOut = 'assets/images/connectiontimeout.png';
final String noInternet = 'assets/images/nointernet.png';
noInternetConnectionMBS(context) {
Size size = MediaQuery.of(context).size;
showModalBottomSheet(
isScrollControlled: true,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40.0),
),
context: context,
builder: (BuildContext bc) {
return Container(
height: size.height * 0.5,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topRight: Radius.circular(40.0),
topLeft: Radius.circular(40.0),
),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: 20),
Stack(
children: [
Container(
height: size.height * 0.3,
alignment: Alignment.center,
child: Image.asset(
typeModal == 'rto' ? connectionTimeOut : noInternet,
fit: BoxFit.contain,
),
),
Align(
alignment: Alignment.topRight,
child: Icon(
Icons.close,
),
),
],
),
Text(
typeModal == 'rto'
? "Connection Time Out"
: 'No Internet Connection',
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
SizedBox(height: 8),
Text(
"Please Try Again",
),
SizedBox(height: 20),
SizedBox(
width: size.width,
child: ElevatedButton(
style:
ElevatedButton.styleFrom(primary: kSecondaryColor),
onPressed: () async {
onTryAgainTap();
Navigator.pop(context);
},
child: Text('Try Again')),
)
//content of modal bottomsheet
],
),
),
);
});
}
}
And call it on my api service like this.
Future<Model> someFunction(
Model requestModel, BuildContext context) async {
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
try {
final response = await http
.post('$baseURL/url',
body: json.encode(requestModel), headers: requestHeaders)
.timeout(Duration(seconds: 30), onTimeout: () {
CustomModalBottomSheet(onTryAgainTap: null, typeModal: 'rto')
.noInternetConnectionMBS(context);
return http.Response('Error', 408);
});
if (response.statusCode == 200) {
}
} on SocketException {
CustomModalBottomSheet(onTryAgainTap: null, typeModal: 'nointernet')
.noInternetConnectionMBS(context);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
