dart 当我导航路线然后返回时,我在BLOC中丢失了状态,为什么?

xeufq47z  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(113)

我有这段代码。总结一下,我正在学习Flutter,我创建这段代码只是为了练习。目标是输入一个TextField,然后按一个FloatingActionBotton,onPressed它会更新一个文本小部件。我使用BloC作为状态管理器。然后,只是为了测试Flutter行为,我创建了一个新的屏幕来回,看看它的工作。我很惊讶地看到,我失去了我的状态,在我的主页,我不能'在按下FloatingActionButton之后,我甚至都没有更新文本小部件。发生了什么?
当我回到主屏幕时,文本小部件消失了,当我按下floatingactionbutton(添加图标)时,我得到一个异常BlocProvider.of(),该异常使用不包含ExampleBloc的上下文调用。

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';

void main() {
  runApp(MaterialApp(
    home: BlocProvider.value(
      value: ExampleBloc(),
      child: Home(),
    ),
  ));
}

class Home extends StatefulWidget {
  Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  late TextEditingController teste;
  late String lol;

  @override
  void initState() {
    teste = TextEditingController();
    lol = 'ola';
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: <Widget>[
          TextField(
            controller: teste,
          ),
          Center(child: BlocBuilder<ExampleBloc, ExampleState>(
            builder: (context, state) {
              return Text(state.exampleString ?? 'null');
            },
          ))
        ],
      ),
      floatingActionButton: Row(
        children: [
          FloatingActionButton(
            onPressed: () {
              lol = teste.text;
              BlocProvider.of<ExampleBloc>(context)
                  .add(ExampleUseEvent(exampleString: lol));
            },
            child: Icon(Icons.add),
          ),
          FloatingActionButton(
            onPressed: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => HEHE()),
            ),
            child: Text('next screen'),
          ),
          FloatingActionButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('pop'),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    teste.dispose();
    super.dispose();
  }
}

class HEHE extends StatelessWidget {
  const HEHE({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: const Center(child: Text('teste')),
      floatingActionButton: Row(
        children: [
          FloatingActionButton(
              onPressed: () => Navigator.of(context).push(
                    MaterialPageRoute(builder: (context) => Home()),
                  ),
              child: Text('next screen')),
        ],
      ),
    );
  }
}

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {
  ExampleBloc() : super(ExampleState()) {
    on<ExampleUseEvent>(exampleFuncion);
  }

  Future<void> exampleFuncion(
    ExampleUseEvent event,
    Emitter<ExampleState> emit,
  ) async {
    emit(state.copyWith(
      exampleString: event.exampleString,
    ));
  }
}

abstract class ExampleEvent {}

class ExampleUseEvent extends ExampleEvent {
  final String exampleString;

  ExampleUseEvent({required this.exampleString});
}

class ExampleState extends Equatable {
  final String? exampleString;

  ExampleState({
    this.exampleString,
  });

  ExampleState copyWith({
    String? exampleString,
  }) {
    return ExampleState(
      exampleString: exampleString ?? this.exampleString,
    );
  }

  @override
  List<Object?> get props => [
        exampleString,
      ];
}
wlzqhblo

wlzqhblo1#

示例块仅在MaterialApp提供时存在于第一页。
切换MaterialApp和BlocProvider.value以获得所需的结果。
MaterialApp包含导航器,导航器包含页面推送时的PageRoutes列表。如果BlocProvider将在MaterialApp之前定义,则它将对所有页面可用。

wribegjk

wribegjk2#

看看我是如何在Flutter中使用块的,我认为你的错误是因为你没有块的状态,所以,数据重置。
example_state.dart

import 'package:equatable/equatable.dart';

class ExampleState extends Equatable {
  final String? exampleString;
  
  ExampleState ({
    this.exampleString,
  });
  
   ExampleState copyWith({
    String? exampleString,
  }){
    return ExampleState(
      exampleString: exampleString?? this.exampleString,
    );
  }

  @override
  List<Object?> get props => [
    exampleString,
  ];
}

example_bloc.dart

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {

  ExampleBloc() : super(ExampleState()) {
    on<ExampleUseEvent>(exampleFuncion);
  }

  Future<void> exampleFuncion(
    ExampleUseEvent event,
    Emitter<ExampleState> emit,
  ) async {
    emit(state.copyWith(
      exampleString: event.exampleString,
    ));
  }
}

example_event.dart

abstract class ExampleEvent {}

class ExampleUseEvent extends ExampleEvent {
  final String exampleString;

  ExampleUseEvent({required this.exampleString});
}

相关问题