我有一个从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语句都不需要更改状态,有时所有语句都需要更改状态,有时只需要更改一些语句。
发布于 2021-11-01 20:46:54
您可以使用以下命令发出状态:
emit(CubitState);
由于您将您的Cubit State声明为一个字符串,因此它将是:
emit("apiResponseAsString");
您可以根据需要发出任意多个状态。因此,对于每个of,您都可以发出相应的字符串。
bloc库的official documentation为您提供了很好的cubits示例。
https://stackoverflow.com/questions/69769803
复制相似问题