如何在颤动中使用 hydated_bloc 保持状态?

Posted

技术标签:

【中文标题】如何在颤动中使用 hydated_bloc 保持状态?【英文标题】:How to keep the state using hydated_bloc in flutter? 【发布时间】:2020-08-01 14:27:52 【问题描述】:

我正在尝试使用库 hydrad_bloc 保持状态,问题是这个库的所有示例都非常基本,我想通过使用示例 api rest 来保持状态,但我仍然无法实现逻辑这个例子:

userbloc_bloc.dart

import 'dart:async';
import 'package:di/users/model/user.dart';
import 'package:di/users/repository/cloud_api_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';

part 'userbloc_event.dart';
part 'userbloc_state.dart';

class UserblocBloc extends HydratedBloc<UserblocEvent, UserblocState> 
  @override
  UserblocState get initialState 
     return super.initialState ?? UserblocInitial();

  

    @override
  UserblocState fromJson(Map<String, dynamic> json) 
    try 
      final usermodel = UserModel.fromJson(json);
      return UserblocLoaded(usermodel);
     catch (_) 
      return null;
    
  

  @override
  Map<String, dynamic> toJson(UserblocState state) 

    if (state is UserblocLoaded) 
      return state.userModel.toJson();
    else
      return null;
    

  

  @override
  Stream<UserblocState> mapEventToState(
    UserblocEvent event,
  ) async* 

  



userbloc_state.dart

part of 'userbloc_bloc.dart';


abstract class UserblocState extends Equatable 
  UserblocState([List props = const[]]);


class UserblocInitial extends UserblocState 
   CloudApiRepository _cloudApiRepository;
  @override
  List<Object> get props => null;
  Future<UserModel> getlistUser() => _cloudApiRepository.getlistUser();


    class UserblocLoading extends UserblocState 
      @override
      Li

st<Object> get props => null;

class UserblocLoaded extends UserblocState 
  final UserModel userModel;
  UserblocLoaded(this.userModel);

  @override
  List<Object> get props => null;


HomeUser.dart

import 'package:di/users/bloc/userbloc/userbloc_bloc.dart';
import 'package:di/users/model/user.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class HomeUser extends StatefulWidget 
  HomeUser(Key key) : super(key: key);

  @override
  _HomeUserState createState() => _HomeUserState();


class _HomeUserState extends State<HomeUser> 
  @override
  Widget build(BuildContext context) 
    return Scaffold(
          body: BlocProvider(create: (context) => UserblocBloc(),
          child: BlocBuilder<UserblocBloc, UserblocState>(
            builder: (BuildContext context, UserblocState state) 
              if (state is UserblocInitial) 
                return showanytext();
               else if (state is UserblocLoading) 
                return buildLoading();
               else if (state is UserblocLoaded) 
                return buildColumnWithData(state.userModel.data);
              
            ,
          ),
        ),
    );
  


Widget buildColumnWithData(List<User> users)
  final user = users;

  return ListView.builder(
    itemCount: users.length,
    itemBuilder: (BuildContext context, int i)

      return Container(
        padding: EdgeInsets.all(15),
        child: Text("$user[i].firstName", style: TextStyle(color:Colors.white),),
        decoration: BoxDecoration(
          color: Colors.black
        ),
      );
    );

Widget buildLoading()

  return Center(
    child: Container(
      child: CircularProgressIndicator(),
    ),
  );


Widget showanytext()

  return Center(
    child: Container(
      child: Text("Construyendo el widget"),
    ),
  );

关于如何保持我的 pad 使用 api 的状态的一些想法,如果我关闭应用程序并在上次关闭她时离开她时在同一个地方重新打开它

【问题讨论】:

【参考方案1】:

很好的问题 - 我有一个非常相似的问题。

简而言之 - 我的 Cubit 状态反映了填写表格并将其发送到 API 的阶段: - 初始、 - 开始、 - 勾选、 - 完成和 - 发送。

由于无法确定 Hydrated Bloc 功能应该返回哪个状态,我实际上将 state 属性作为枚举添加到 Cubit State 以反映 Cubit“最后一次看到”的状态以及在某些条件下从存储库返回相同的状态。有了它,最后填写的字段将被提取。 这听起来和看起来像是一种冗余,但我想不出更好的解决方案。我很乐意听到一些想法:)

这是 Cubit 的 State 类声明:

part of 'job_realization_cubit.dart';

enum Status 
  initial,
  started,
  tick,
  completed,
  sent,


abstract class JobRealizationState extends Equatable 
  const JobRealizationState(
    this.status,
    this.timeLeft,
    this.jobRealization,
    this.message,
  );
  final Status status;
  final int timeLeft;
  final JobRealization jobRealization;
  final String message;

  @override
  List<Object> get props => [status, timeLeft, jobRealization, message];


class JobRealizationInitial extends JobRealizationState 
  const JobRealizationInitial();


class JobRealizationStarted extends JobRealizationState 
  const JobRealizationStarted(status, timeLeft, jobRealization, message)
      : super(
          status: status,
          timeLeft: timeLeft,
          jobRealization: jobRealization,
          message: message,
        );


//Timekeeping after start of Realization
class JobRealizationTick extends JobRealizationState 
  const JobRealizationTick(status, timeLeft, jobRealization, message)
      : super(
          status: status,
          timeLeft: timeLeft,
          jobRealization: jobRealization,
          message: message,
        );



class JobRealizationDone extends JobRealizationState 
  const JobRealizationDone(status, timeLeft, jobRealization, message)
      : super(
          status: status,
          timeLeft: timeLeft,
          jobRealization: jobRealization,
          message: message,
        );


class JobRealizationSent extends JobRealizationState 
  const JobRealizationSent(status, timeLeft, jobRealization, message)
      : super(
          status: status,
          timeLeft: timeLeft,
          jobRealization: jobRealization,
          message: message,
        );


class JobRealizationSendError extends JobRealizationState 
  const JobRealizationSendError(status, timeLeft, jobRealization, message)
      : super(
          status: status,
          timeLeft: timeLeft,
          jobRealization: jobRealization,
          message: message,
        );

【讨论】:

JobRealization 类由什么组成?

以上是关于如何在颤动中使用 hydated_bloc 保持状态?的主要内容,如果未能解决你的问题,请参考以下文章

如何在颤动中取消焦点文本字段?

如何在颤动中设置 showModalBottomSheet 宽度

移动到其他页面时无法保持底部导航栏颤动

不仅在颤动中单击它时,如何始终在文本字段中显示提示?

如何在颤动中更改容器小部件中的背景图像

颤动的firebase登录问题