在 Jetpack Compose 中可以很方便地与 Retrofit 进行融合来实现网络请求并在界面上展示结果。以下是具体步骤:
一、添加依赖
首先,确保在项目的 build.gradle
文件中添加了 Retrofit 和相关的依赖项,例如:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
二、创建 Retrofit 实例
通常在一个独立的模块或者类中创建 Retrofit 实例,以便进行网络请求的配置和管理。
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
private const val BASE_URL = "https://your-api-url.com/"
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
三、定义接口
创建一个接口来定义网络请求的方法,例如:
import retrofit2.Call
import retrofit2.http.GET
interface ApiService {
@GET("your-endpoint")
fun getSomeData(): Call<YourResponseModel>
}