[英]How can a Flutter Cubit emit multiple state changes
我有一個從 API 檢索 json 數據的 Cubit。 它處理數據並基於處理,將需要更改多個小部件的狀態。
本質上,使用一些 if 語句,如果數據符合某些標准,則需要發出狀態更改。
此代碼示例展示了這個想法,但我不確定如何在 if 語句中實際滿足需求。
import 'dart:convert';
import 'package:bloc/bloc.dart';
import 'package:dio/dio.dart';
class ProcessingCubit extends Cubit<String> {
ProcessingCubit() : super("");
void getDataFromAPI() async {
Response response;
var dio = Dio();
response = await dio.get(
'http://our.internalserver.com:8080/api/getdata.php',
queryParameters: {});
var parsedjsonresponse = json.decode(response.data.toString());
//the json returned is an array of objects. For this code example,
//we're only going through slot 0 of the array of objects
if (!parsedjsonresponse['ourdata'].isEmpty) {
print(parsedjsonresponse['ourdata']);
}
if (!parsedjsonresponse['ourdata'][0]['code'] == "001") {
//emit state for this code, so that the necessary widget
//will show something
}
if (!parsedjsonresponse['ourdata'][0]['code'] == "002") {
//emit state for this code, so that the necessary widget will
//show something (different widget than the "if" block above
}
if (!parsedjsonresponse['ourdata'][0]['alert'] == "1") {
//emit state for this alert so that the alert widget
//will show something
}
}
}
有時,所有 if 語句都不需要更改狀態,有時可能需要全部更改,有時只需要更改一些。
您可以使用以下方式發出狀態:
emit(CubitState);
由於您將 Cubit 狀態聲明為字符串,因此將是:
emit("apiResponseAsString");
您可以根據需要發出盡可能多的狀態。 因此,對於您的每個 if,您都可以發出相應的字符串。
bloc 庫的官方文檔為您提供了關於肘的絕佳示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.