首页 > 解决方案 > 如何在 jetpack compose 中传递来自 Firestore 的查询的参数

问题描述

我的项目中有一个查询来检索游戏列表并将其显示在一个lazyColumn 中。当我查询整个集合时它工作正常,但我想放置一个 whereIn 子句,它需要我必须在片段中传递的 2 个参数,但我不知道如何使用 Jetpack Compose 传递它。

以下是已经存在且正在运行的查询:

@Module
@InstallIn(SingletonComponent::class)
object AppModule {
    @Provides
    @Named("queryGame")
    fun provideGetAllGames(): Query =
        FirebaseFirestore.getInstance()
                .collection(GAMES)
}
@Singleton
class PlayersRepository @Inject constructor(  
    private val queryGame: Query,
) {
 fun getPlayerFromFirestore(): DataOrException<Task<DocumentSnapshot>, Exception> {
        val dataOrException = DataOrException<Task<DocumentSnapshot>, Exception>()
        try {
            dataOrException.data = getUser.get()
        } catch (e: FirebaseFirestoreException) {
            dataOrException.e = e
        }
        return dataOrException
    }
@HiltViewModel
class GamesViewModel @Inject constructor(
    private val repository: PlayersRepository
): ViewModel() {
 val data: MutableState<DataOrException<List<Game>, Exception>> = mutableStateOf(
        DataOrException(
            listOf(),
            Exception("")
        )
    )

    init{
       getAllGames()
    }

   fun getAllGames() {
        viewModelScope.launch {
            data.value = repository.getAllGames()
        }
    }
@AndroidEntryPoint
class GameFragment : Fragment() {

    private val viewModel: GamesViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
     return ComposeView(requireContext()).apply {
            setContent {
                      val games = viewModel.data.value.data
LazyColumn{
           items(games!!){ game ->
            GameResults(game)
    }
 }

我需要在 appModule 中添加 .whereIn(PLAYERS, listOf(user1 + " " + user2, user2 + " " + user1)) 但我不知道如何在片段上传递 user1 和 user2。我怎样才能做到这一点?

标签: androidfirebasekotlingoogle-cloud-firestoreandroid-jetpack-compose

解决方案


我需要在 appModule 中添加 .whereIn(PLAYERS, listOf(user1 + "" + user2, user2 + "" + user1))

您不能将动态数据传递到 AppModule 文件中。因此,要使用 Query 对象从 Firestore 获取数据,您需要.whereIn()在存储库类中添加该调用。看到您已经将“queryGame”对象(实际上是一个 CollectionReference 对象)注入到您的存储库类中,您可以使用以下代码行:

dataOrException.data = queryGame.whereIn(PLAYERS, listOf(user1 + "" + user2, user2 + "" + user1)).get()

不要忘记在使用此查询的方法中同时传递“user1”和“user2”对象。


推荐阅读