1

I am making an app using the BLoC architecture using the flutter_bloc package, but I need to get data from a database, which is asynchronous, meaning I can't initialize the BLoC with data from my database. Is there a way I can do this? My BLoC class text is

import 'package:countdown/database/utils.dart';
import 'package:countdown/events/countdown_event.dart';
import 'package:countdown/models/countdown.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class HomeBloc extends Bloc<CountdownEvent, List<Countdown>> {
   @override
  // TODO: implement initialState
  List<Countdown> get initialState => DatabaseUtils.getCountdowns();


  @override
  Stream<List<Countdown>> mapEventToState(CountdownEvent event) {
  }
}

I know this is very similar to This Question, but that question's answers don't have any code snippets which would be very helpful.

Yudhishthir Singh
  • 2,941
  • 2
  • 23
  • 42
Nailuj29
  • 750
  • 1
  • 10
  • 28
  • create one separate async function and call if from initState(). – xbadal May 18 '20 at 22:28
  • initState() would still have to return a Future, which makes it an invalid override of the parent class. – Nailuj29 May 18 '20 at 23:39
  • *" but I need to get data from a database, which is asynchronous,"* - so you need to read [this](https://dart.dev/codelabs/async-await) amd [this](https://dart.dev/tutorials/language/streams) – pskink May 19 '20 at 03:57
  • The initialState has to be an instance of the type parameter State, which in my case is a List – Nailuj29 May 19 '20 at 13:02
  • and whats wrong with `[]` in that case? – pskink May 19 '20 at 13:05
  • I would like for the initial state of the BLoC to be the data in the DB, so an empty list would not work. – Nailuj29 May 19 '20 at 13:19

1 Answers1

1

create one separate async function and call if from initState(). this is my code you can call your method according to use.

  @override
  HomeState get initialState {
    _checkLocationSettings();
    return InitialHomeState();
  }



_checkLocationSettings() async {
locationUpdateSetting = await repository.isLocationUpdateOn();}
xbadal
  • 1,284
  • 2
  • 11
  • 24