1

我有这个应用程序,其中有一个介绍屏幕,如果用户已经跳过一次,我想隐藏它。我正在将 bloc 与提供者一起使用。我的问题是当我热重启应用程序时连接状态发生了两次变化,而我已经花了几个小时而不了解原因。

这是我的代码:

我的主要课程

void main() => runApp(StatsApp());

class StatsApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => IntroProvider(),
        )
      ],
      child: Consumer<IntroProvider>(builder: (context, value, child) {
        return MaterialApp(
            home: FutureBuilder(
          future: value.bloc.checkSkipped(),
          builder: (BuildContext context, snapshot) {
            print(snapshot.connectionState);
            print(snapshot.data);
            return SplashScreen();
          },
        ));
      }),
    );
  }
}

我的集团

enum IntroEvents {
  ReadLocalStorage,
  SetIntroSkipped,
}

class IntroBloc extends Bloc<IntroEvents, bool> {
  PrefsManager _prefsManager = PrefsManager.instance;

  Future<bool> checkSkipped() async {
    this.add(IntroEvents.ReadLocalStorage);
    final skipped =
        await _prefsManager.getValue(PrefTypes.Bool, "skippedIntro");
    return skipped;
  }

  @override
  // TODO: implement initialState
  bool get initialState => false;

  @override
  Stream<bool> mapEventToState(IntroEvents event) async* {
    switch (event) {
      case IntroEvents.SetIntroSkipped:
        _prefsManager.setValue(PrefTypes.Bool, "skippedIntro", true);
        yield true;
        break;
      case IntroEvents.ReadLocalStorage:
        final skipped =
            await _prefsManager.getValue(PrefTypes.Bool, "skippedIntro");
        yield skipped;
        break;
      default:
        print("wtffffff");
    }
  }
}

我的提供者

class IntroProvider with ChangeNotifier {
  IntroBloc _bloc;

  IntroProvider(){
    print("called IntroProvider");
    _bloc = IntroBloc();
  }

  IntroBloc get bloc => _bloc;
}

任何帮助将不胜感激。

4

1 回答 1

0

使用快照时,您可以检查snapshot.hasData. 通常,当快照在语句中包含数据时,您会包装要运行的功能,并在没有数据时if提供某种默认值Widget

FutureBuilder(
  future: value.bloc.checkSkipped(),
  builder: (BuildContext context, snapshot) {
    print(snapshot.connectionState);

    if (snapshot.hasData) {
      print(snapshot.data);
    }

    return SplashScreen();
  },
);
于 2020-05-09T14:02:26.093 回答