Search code examples
flutterapihttp-postretrofitriverpod

How to do POST API in flutter using Dio ,retrofit and riverpod?


Can someone help me with the POST API request in flutter using dio, riverpod and retrofit , its quite confusing. It will be very helpful if someone explain the whole flow with code

Im not sure about the code, can someone help with thee code


Solution

  • Using Riverpod 2.x

    
    @riverpod
    Future<MyModel> httpGet(HttpGetRef ref, String url) async {
        return await _doGet(url); 
    }
    
    Future<MyModel> _doGet(String url) async {
         // use whatever lib for HTTP
        // get the response and deserialize
       return deserialized;
    }
    
    

    now in a ConsumerWidget build method, you can

    final responseFuture = ref.watch(httpGetProvider(url).future);
    
    return Column(children: [
        FutureBuilder<MyModel>(
            future: responseFuture,
            builder: (context, snapshot) {
                if (!snapshot.hasData) return LoadingWidget();
                return DisplayDataWidget(data:snapshot.data!);
            }),
    
        Button(
            text: "Refresh", 
            onClick: () => ref.invalidate(httpGetProvider(url))
        )
        ]);
    

    Depending on your app, you may want to wrap the provider in another provider, like .. say accountInfoProvider so your widgets don't have to know the url. You can also decide to implement caching .etc. in a provider in the middle as well.