我有一个从 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 语句需要改变状态,有时可能全部都需要,有时只需要一些。