【问题标题】:How can a Flutter Cubit emit multiple state changesFlutter Cubit 如何发出多个状态变化
【发布时间】:2021-12-14 14:00:03
【问题描述】:

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

【问题讨论】:

    标签: flutter dart bloc flutter-bloc cubit


    【解决方案1】:

    您可以使用以下方式发出状态:

    emit(CubitState);

    既然你声明你的 Cubit State 是一个字符串,那就是:

    emit("apiResponseAsString");

    您可以根据需要发出尽可能多的状态。因此,对于您的每个 if,您都可以发出相应的字符串。

    bloc 图书馆的official documentation 为您提供了很好的肘位示例。

    【讨论】:

    • 如果这个 Cubit 将多个状态作为字符串发出,每个将接收一个发出的字符串的 BlocBuilder 如何知道它正在接收哪个字符串?换句话说,每个 BlocBuilder 如何从 Cubit 中获取正确的字符串?
    猜你喜欢
    • 2022-10-13
    • 2022-01-21
    • 2021-09-03
    • 2022-12-19
    • 2021-01-10
    • 2022-12-14
    • 2021-02-12
    • 2021-06-20
    • 2020-12-15
    相关资源
    最近更新 更多