flutter_bloc,bloc_provider无法与底部工作表一起使用

时间:2020-10-09 03:13:07

标签: flutter flutter-bloc flutter-state flutter-showmodalbottomsheet

问题

我用以下文件复制了问题。该应用程序有一个菜单。菜单是一个内部带有按钮的modalBottomSheet。该按钮从肘部调用方法,该方法向主屏幕发出状态。在这种情况下,当BlocListener检测到状态时,它将显示一个小吃店。 Bloc在整个应用程序中与BlocProvider共享。

该按钮仅在第一次使用。然后它不再起作用。为什么?我该如何解决?

依赖项

flutter_bloc: ^6.0.3
equatable: ^0.2.0
meta: ^1.1.6

main.dart

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: BlocProvider(
        create: (_) => TestCubit(),
        child: MainScreen(),
      ),
    );
  }
}

main_screen.dart

class MainScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocListener(
          cubit: context.bloc<TestCubit>(),
          listener: (context, state) {
            if (state is TestStateSnackBar) {
              final snackBar = SnackBar(content: Text("I only work once"));
              Scaffold.of(context).showSnackBar(snackBar);
            }
          },
          child: Center(
            child: FlutterLogo(),
          )),
      bottomNavigationBar: BottomAppBar(
        child: Row(
          children: [
            IconButton(
              icon: Icon(Icons.menu),
              onPressed: () => showModalBottomSheet(
                context: context,
                builder: (_) => BlocProvider(
                  create: (_) => context.bloc<TestCubit>(),
                  child: Menu(),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

menu.dart

class Menu extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: FlatButton(
        child: Text("Click to show snack bar"),
        onPressed: () => context.bloc<TestCubit>().showSnackBar(),
      ),
    );
  }

test_cubit.dart

class TestCubit extends Cubit<TestState>{

  TestCubit() : super(TestStateInitial());

  showSnackBar() => emit(TestStateSnackBar());
}

test_state.dart

@immutable
abstract class TestState extends Equatable {
  TestState([List props = const []]) : super(props);
}

class TestStateInitial extends TestState {
  @override
  String toString() => 'Test Initial';
}

class TestStateSnackBar extends TestState {

  @override
  String toString() => 'Test SnackBar';
}

0 个答案:

没有答案