MutableLiveData<MutableList<String>>() 中未添加值

Values are not added in MutableLiveData<MutableList<String>>()

我正在使用一个片段和视图模型,当从我的片段调用函数时,列表值不会在 viemodel 中更新。

这是我的片段

class SettingsFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val binding = FragmentSettingsBinding.inflate(inflater)
    val application = requireNotNull(this.activity).application
    val dataSource = UserInfoDatabase.getInstance(application).userInfoDao
    val viewModelFactory = SettingsViewModelFactory(dataSource, application)
    val settingsViewModel = ViewModelProvider(this, viewModelFactory).get(SettingsViewModel::class.java)
    binding.settingsViewModel = settingsViewModel
    binding.lifecycleOwner = this
    settingsViewModel.addValueToList("hello")
  }
}

这是我的 ViewModel

class SettingsViewModel(val database: UserInfoDatabaseDao, application: Application): AndroidViewModel(application){
    private val _sectionList = MutableLiveData<MutableList<String>>()
    val sectionList: MutableLiveData<MutableList<String>>
        get() = _sectionList
    fun addValueToList(listValue: String){
    _sectionList.value?.add(listValue)
    }
 } 

在尝试向列表中添加值后,当我尝试从我的 viewModel 中将 toast 消息打印为 _sectionList.value.toString() 时,它显示为 null。

在此先感谢您的帮助..

这是因为你还没有初始化MutableList<>()

class SettingsViewModel(val database: UserInfoDatabaseDao, application: Application): AndroidViewModel(application){

    private val _sectionList = MutableLiveData<MutableList<String>>()

    val sectionList: MutableLiveData<MutableList<String>>
        get() = _sectionList

    fun addValueToList(listValue: String){

       // In the following line: _sectionList.value is still null, so this will 
       // never call the add
        _sectionList.value?.add(listValue)
    }
 } 

如果您初始化为:

init {
    _sectionList.value = mutableListOf<String>()
}

它应该很有希望工作。