Dio Connectivity Retry Interceptor – Flutter Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
performing HTTP requests is all fun and games until there is no internet connection sure you can display a set error message or a Chrome dinosaur to the user but wouldn't it be better to take the initiative and automatically retry the request when the user connects to a Wi-Fi network or enables mobile data this is precisely what we are going to implement in this tutorial hello welcome to resew kagra where you are getting prepares for real app development so that you will get freelance clients or job and be confident about the apps you built so subscribe and hit the bell to join us in our quest for becoming in demand flutter developers in this tutorial we are going to build a very simple app which will be able to request data from a very simple JSON placeholder API and it all works very nicely when there is some sort of an internet connection however when we disable Internet and then request data what's gonna happen is that we're not going to get any error message popping up on us instead we are going to schedule a retry of the request and whenever internet connection comes back we're automatically going to retry the request and the user doesn't have to do anything like pressing a retry button everything is going to be handled for the user we're going to accomplish this with Daioh and also the connectivity package and actually this is the starter project which is prepared for you together with all of the packages already present in the pub spec Daddy ammo so that's dial and connectivity and if you want to get this starter project with this very nice-looking UI already done for you be sure to check out the written tutorial from the link in the video description because there is the starter project and also over there you can go through this lesson at your own pace get all of the code rewrite over here and really just take a look through this lesson on your terms so let's get going we are going to use the dial package and not the sort of default HTTP package to perform the requests that's because Daioh supports interceptors and that's precisely what we need because we want to intercept any errors which occur during the request actually when I run this app which is coming from the start project which simply just calls dial gets and some sort of a JSON placeholder posts and we get the first title of the post it's very simple what we are doing here when I run this the UI looks exactly the same as that of the already finished app but what happens is that when we request data with internet connection disabled we are going to get a socket exception and if we come back to the app well we still see this circle spinning but when we enable Internet the request is now going to get retried automatically so we just got sucker exception we didn't even handle it and yeah retry does not happen that's because we need to add an interceptor to this dial client which will intercept all the errors for us and retry the request on users behalf so let's create that interceptor shall we we're going to create a new folder called Interceptor and let's just create a new file under there it's gonna be called retry interceptor down tart and you'd really do not need to know much about dial we are now getting deep into it we are just going to focus on interceptors so even if you have no previous dier dier experience you're going to be good to go with this tutorial so in order to create an interceptor with dial we're gonna create a simple class retry on connection change interceptor it's going to extend interceptor which comes from dial and interceptors intercept every possible thing which goes on in the dial client and they do it with callback methods if we go into the interceptor class definition we see that we can override on request on response and on error callbacks and of course because we are really just trying to know when the socket exception happens which indicates that there is no internet connection currently we really just want to override the on error callback because we are interested in errors after all so let's override on error which will grant us a dial error and for now we're just gonna leave this thing empty we actually do not need to call the super classes on error method and you may think that right inside this on error callback as it is looking now we can start using the connectivity package right something like this and use the on connectivity change stream which updates whenever the user connects or disconnects from a mobile data network or from a Wi-Fi network and so on well no that's not true we cannot just straight start scheduling the retry of a request right here that's because this on error callback will run undiscriminating single possible error which may occur when performing a request this includes errors coming back from the server such as 404 not found or 401 unauthenticated I think and so many things which can go wrong on this River and we want this interceptors on error callback run only specifically for when a socket exception occurs so we need to have a way to find out if this dial error which is passed into the callback actually represents the socket exception for a we're gonna create bull returning method should retry it's gonna be private and it's going to accept dial error let's call it error also and probably we're going to simply return that we should retry if error type is equal to dial error type which is an enum right so dial error type that default and as you can see in the documentation default means some other error and some other error includes errors which come back from the system for example the socket exception and also if the error that error is not know and lastly also error dot error is the socket exception exception call we just need to check if error is not more because possibly it can happen that error is no and we definitely do not want to cause a nullpointerexception when we are checking for the socket exception that would be catastrophic so what we want to do now is simply check if we should retry for the error then we're going to perform the scheduling of the request whenever the connectivity status changes back to being connected and otherwise if we should not retry what we're gonna do is that we're gonna return the error simply back on changed and for some reason yeah we need to make this function asynchronous that's kind of obvious and with this done whenever we should not retry the error which does not interest us is going to be returned from this callback and they will simply push it to the caller of the get method for example or the post method so we do not need to actually add an else statement here because but we can but we don't need to because we are actually going to return something from this if statement also right let's keep this terse and now let's go on to implementing the request retry err because having the Interceptor is only one part of the game that's because we need to use the connectivity package as I've already outlined briefly and use the on connectivity change stream listen to it and whenever the connectivity changed to be connected we're going to retry the request however I do not really like to put multiple functionalities into just one class wanna follow the single responsibility principle so we're now going to put this connectivity logic right over to this Interceptor instead we are going to create a new file and a new class for it and it's going to be called die oak and activity request retrial so let's create one such file right here under the interceptor folder Daioh connectivity request retry that dart and we're going to create class file I have these kinds of shortcuts in place so we have just created a class dial connectivity request reach higher and we are going to be its dependencies well we definitely need to have a dial client present here so that we can perform the request one more time we're basically going to do something similar as call and I owe that get but for the second time we are going to retry their request so final dial Daioh is one dependency let's import it and the second dependency is of course the connectivity class and I'll just call it connectivity and we're going to create a constructor for it and let's also make beasts required so we're going to use the magic of dart formatter require the largest import whatever flutter foundation for the required annotation and now this class will have only one method and that is going to be schedule request retry which is going to return a future response this response is the very response which also comes out of the regular get call on the dial client so we're religious returning an HTTP response which is gonna be retried in this retrial class so this method will be called schedule request retry of course with lower case T and it needs to accept some sort of an object which represents the failed request right because this interceptor will intercept any sort of an error which goes on whenever we request something so how can we actually get the fail request and what is its type well we can take a look the error object actually holds a very handy field request which represents the failed request and this is of type request options so this means that our requests retire needs to take in request options and is also going to be a sink cool now comes the time to finally use the stream which I have been talking about so much so that's gonna be the unconnected little changed stream and we want to listen to it and it's going to pass us a connectivity result and in this closure in this callback we are going to perform the retry logic so what can we do here well first of all we want to retry the request only when the connectivity changes to be connected so this connectivity result which is passed here is of type connectivity result which is actually an enum so we can check if connectivity result is connectivity result that none or should we say is not so basically if connectivity result is not none which means that we are not disconnected I know double negatives but whatever so it means when we are connected only then we want to retry the request cool so how can we retry the request well we can called i/o and over in the UI we are calling the i/o that gets to perform a get request right we want to get something but this would make this retry er only work with get requests but what if we want to actually retry a post request or a patch request well that would not work all that great that's why we are now going to call get instead we are just going to call request and we are going to paste all of the methods like gets put post and all of that from our request patience object which holds every single data which is useful for the request which we want to retry here so first we want to specify the path for the request we're going to say request options that path and then we want to populate all of the other named parameters which are present on this request method and actually I'm just going to copy them from the written tutorial and you can do the same because yeah as you can see there's just a lot of them here so we wanna copy over the canceled token data and all of that other stuff and we get everything from the request options which are the request options of the failed request which we now want to retry okay so we are calling diode odd request but something doesn't play right here we are not returning any response from our schedule requests retry method actually we're now returning anything from this method and we surely do want to return this response but we cannot do that because we are inside a closure and the closure is inside a listen callback which is of type voice so we cannot really put a return statement straight out to this closure we need to create some other way to get this result of the request out from the schedule request retry method so if we cannot straight out return something from a closure what can we do well we can use a completer completers are very useful for making synchronous code asynchronous and also for occasions like this where you have a closure and you want to return something from outside the closure so we are going to create final response computer it's gonna be of tight completer response and let's import the dart async in order to have this completed class here and completers are very simple all they do is that they can be completed of course and they can be completed with some sort of a future so we're gonna go into here into this closure and right response completer that complete with the diode request call and as you can see the complete method takes a future or already completed value of type response and what this will do is that whenever we come here into this closure whenever the on connectivity changed stream emits a new value and that value says that we are already connected to some sort of a network our completers future will complete and therefore when we await the future somewhere in the UI or whenever we are going to do what the futures do whenever the future completes the wait block will return a regular value and we're going to continue with the execution of the code as if it were synchronous so now the last thing we need to do in order to make this all happen is to actually return the completers future from the methods cool with this done we might think that we have just implemented everything we need to make this work of course after we return it that's kinda obvious but actually there is still one more thing we can do in this request retrial class that's because if you take a look at this whenever we schedule request retry these runs this closure gets created and actually we would retry the request indefinitely whenever the connectivity status changes from connected to not connected and then back to connect it so because we definitely do now want to retry the request multiple times but only the first time we get connected after being disconnected we sort of need to get rid of this listener on the stream after the first time we have scheduled a request so what can we do well we can put this stream subscription which we get out of the lesson call into variable so stream subscription stream subscription will be its name and we're going to store it and now whenever the connectivity result is none is not none actually for the first time we're just going to call stream subscription that cancel and this way after the first retry this stream subscription this closure will never run again awesome so let's put this all together and just remember that if this is quite a lot for you to comprehend on the first try you can always take a look at all of this code and also on the fully written tutorial from the link in the video description now let's go back to the retry interceptor and we are going to add the final diode connectivity request retry or dependency we're going to populate it through a constructor and now we can use this request retry er whenever we should retry so what are we gonna do here we're going to do a try-catch block and inside the try block we are going to simply return request Rick trier dots schedule request retry and pass in the request options from the error object so again this is the failed request which we want to retry and as you can see we are returning the response back from this on error callback and if some other exception happens from the request retry err we are going to simply return the exception from this on error callback so for example if some sort of a situation happened that we would get another socket exception inside the schedule request retry for some reason that second socket exception would be returned as usual from the get request and we would simply be able to catch it in the UI as usual actually the second socket exception can really happen because the connectivity package does not put any guarantees that if the connectivity result is not none that there is actually some sort of an internet connection all it means is that the user is connected to a network but as you know the network is still present even if you plug out the when cable from your router so your router can emit Wi-Fi signal but that signal is actually leading nowhere only to your local area network not to the wide area network so you need to keep that in mind connectivity package does not guarantee that you are actually connected to internet to the world wide web we could say and now that we have implemented the Interceptor and also very trier all we need to do is to jump back to main dab dirt and block our interceptor to the dial instance and again you can get this main down dart file from the written tutorial as a starter project so all we need to do here is to grab our dial instance which we are instantiating a few lines above and we're going to grab interceptors and add a new element to over there our interceptor is called retry on connection change interceptor we need to populate it with a request retry err oh I did not make this parameter names I probably should so let's do that right now it's required let's import it and now we're golden so we need to populate the request retire with our diode connectivity request retire and that in turn takes in eight connectivity let's instantiate that and also diode and of course you would not do this manually in the real app you would instead use some sort of a dependency injection system like injectable to populate these parameters of the constructor and now we have introduced some sort of an error to our project the not sure why oh I forgot about what oh there should not be the semicolon that's kind of obvious but anyway we've just added the Interceptor and when I had restarts the app now out from the emulator we request data when we have in red it works as expected but when we go into airplane mode and now request data yeah we still get the socket exception that's not an issue though that's only happening because we are catching uncaught exception in vs code and for some reason vs code things that this exception is not caught but anyway when we hop through this when we continue in the execution of the code and now come back to our emulator we can see that the circle is spinning but what's different now is that when we disable airplane mode you will stop this circle from spinning and actually the request will be retried successfully and as you can see that's precisely what happened so we know our code works nicely to go through this tutorial at your own pace once again and to also get all of the code check out the written tutorial from the link in the description and you have just learned how to create retry on connection change Interceptor using the diode client for HTTP in flutter and I am absolutely certain that doing something like this will enhance the user experience of your apps because automatically trying is in my opinion much better than prompting the user to press a button to retry the request himself or herself and if you are serious while becoming a great flower developer who can build real apps for clients or at the job go to flutter that education and link is also in the video description to get the top curated for news and resources aimed at improving your app development career and over there you can also subscribe to my mailing list to get the best photo resources delivered we Klee right into your inbox and if you don't want to miss more tutorials like this where we tackle important topics for flower developers be sure to subscribe to this channel and also join notification squad by hitting the bell button to make sure you grow your flower skills because here are reso colder I am determined to provide you with the best tutorials and resources so that you will become an in-demand flutter developer if this video helps you with implementing this kind of an interceptor give it a like and also share with our developers who are surely going to find it beneficial to leave a comment if you have anything to say and see you in the next [Music]
Info
Channel: Reso Coder
Views: 29,119
Rating: undefined out of 5
Keywords: resocoder, tutorial, programming, code, programming tutorial, flutter, flutter tutorial, flutter http, flutter http request, flutter http request rest api, flutter dio tutorial, flutter dio example, flutter dio interceptor, flutter retry request, flutter request api, flutter dio retry request, dio retry interceptor, flutter http error handling, flutter socket exception
Id: qkN0kcZxeVc
Channel Id: undefined
Length: 30min 25sec (1825 seconds)
Published: Mon Mar 23 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.