How to call bloc inside initState method? - flutter

I need to call the fetchProfile() method and get the profileState.user data in the initState method right after the page opens. Tell me, how can I write this correctly, how can I correctly call Cubit inside the initState method?
#override
void initState() {
SchedulerBinding.instance.addPostFrameCallback((_) {
_emailDialog();
});
super.initState();
}
cubit
class ProfileCubit extends Cubit<ProfileState> {
final UserRepository _repository;
ProfileCubit(this._repository) : super(ProfileInitial());
Future fetchProfile() async {
try {
final User? user = await _repository.me();
if(user != null) {
emit(ProfileLoaded(user));
} else {
emit(ProfileError());
}
} catch (_) {
emit(ProfileError());
}
}
state
abstract class ProfileState {}
class ProfileInitial extends ProfileState {}
class ProfileLoaded extends ProfileState {
final User? user;
ProfileLoaded(this.user);
}
class ProfileError extends ProfileState {}

If your intention is to run the method fetchProfile directly when the widget (page in this case) will be built, I'd run the method when providing the bloc using cascade notation as such:
home: BlocProvider(
create: (_) => ProfileCubit()..fetchProfile(),
child: YourPageOrWidget(),
),
The fetchProfile() method will be called as soon as the Bloc/Cubit is created.
Note that by default, the cubit is created lazily, so it will be created when needed by a BlocBuilder or similar. You can toggle that so it isn't created lazily.

You can check the Readme of flutter_bloc. There is a full tutorial and you can learn a lot.
#override
void initState() {
super.initState();
context.read<ProfileCubit>().fetchProfile()
}
Wrap BlocListener for your widget tree. You can listen to ProfileLoaded state here and get the user data immediately.
BlocListener<ProfileCubit, ProfileState >(
listener: (context, state) {
// Do whatever you want.
},
child: Container(),
)

Related

Flutter RepositoryProvider and Hive LateInitializationError

I have app where I am using Bloc and Hive.
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appDocumentDirectory =
await path_provider.getApplicationDocumentsDirectory();
Hive.init(appDocumentDirectory.path);
runApp(
const MyApp(),
);
}
On MyApp widget registered MultiRepositoryProvider
return MultiRepositoryProvider(
providers: [
RepositoryProvider(create: (context) => AccountService()),
],
child: MultiBlocProvider(
providers: [
BlocProvider<AccountBloc>(
create: (context) => AccountBloc(context.read<AccountService>()),
),
],
child: MaterialApp(
home: const AppPage(),
),
),
);
AppPage Contains bottomNavigationBar and some pages
account.dart
class AccountService {
late Box<Account> _accounts;
AccountService() {
init();
}
Future<void> init() async {
Hive.registerAdapter(AccountAdapter());
_accounts = await Hive.openBox<Account>('accounts');
}
On appPage have BlocBuilder
BlocBuilder<AccountBloc, AccountState>(
builder: (context, state) {
if (state.accountStatus == AccountStatus.loading) {
return const CircularProgressIndicator();
} else if (state.accountStatus == AccountStatus.error) {
Future.delayed(Duration.zero, () {
errorDialog(context, state.error);
});
}
return SingleChildScrollView(....
When app first loaded I receive LateInitializationError that late Box <Account> _accounts from account Repository not initialized. But as soon as I navigate to another page and go back, the Box <Account> _accounts are initialized and the data appears.
How can I avoid this error and initialize the Hive box on application load?
Can you try this? I think you need to await Hive init function
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appDocumentDirectory =
await path_provider.getApplicationDocumentsDirectory();
await Hive.init(appDocumentDirectory.path);
runApp(
const MyApp(),
);
}
It's been like 7 months, but if you are still looking for an answer, not sure if it's optimal but below should work.
My understanding on the issue you are having is that the reason why there is that "LateInitializationError" is because that your init function call in your constructor is asynchronously invoked without await for its result. As a result, there is a possibility that when you are calling functions on the box, the initialisation is not yet finished. When you navigate to another page and go back, the function init run happened to be finished. Hence, the error is gone. The complexity here is that constructor can not be marked as async for you to use that await keyword. Since you are using bloc, one possible workaround is to call the init function of your repo when bloc is in init state.
For demo purpose I defined below bloc states and events,
you can absolutely change them based on your needs.
// bloc states
abstract class AccountState{}
class InitState extends AccountState{}
class LoadedState extends AccountState{
LoadedState(this.accounts);
final List<Account> accounts;
}
class LoadingErrorState extends AccountState{}
//bloc events
abstract class AccountEvent {}
class InitEvent extends AccountEvent {}
... // other events
in your bloc logic you can call the init function from you repo on InitEvent
class AccountBloc extends Bloc<AccountEvent, AccountState> {
AccountBloc(this.repo) : super(InitState()) {
on<InitEvent>((event, emit) async {
await repo.init();
emit(LoadedState(account: repo.getAccounts()));
});
...// define handlers for other events
}
final AccountRepository repo;
}
in your service class you can remove the init from the constructor like:
class AccountService {
late Box<Account> _accounts;
AccountService();
Future<void> init() async {
Hive.registerAdapter(AccountAdapter());
_accounts = await Hive.openBox<Account>('accounts');
}
List<Account> getAccounts(){
return _accounts.values.toList();
}
}
Then in your bloc builder, you can add init event to your bloc when the state is InitState as below:
BlocBuilder<AccountBloc, AccountState>(
builder: (context, state) {
if (state is InitState) {
context.read<AccountBloc>.add(InitEvent());
return const CircularProgressIndicator();
} else if (state is LoadingErrorState) {
Future.delayed(Duration.zero, () {
errorDialog(context, state.error);
});
}
else if (state is LoadedState){
return SingleChildScrollView(....
}
Also, FYI, you can if you want the init to be called when the object of your account service is instantiated, you can take a look at below answer:
https://stackoverflow.com/a/59304510/16584569
However, you still going to need to await for the initialisation of your service. One possible way is just do it in your main function and pass down to your app, but it makes the structure of your code messy and when you want to swap to another repo, you need to remember to change code in main function as well.

How can i call my provider model into initState method

i have several widgets use my provider as a condition , and i need one call to access my provider to whole widget from init state instead of wrapping every widget into my provider and it's consumer
this is my provider
class ProviderForFiltter extends ChangeNotifier {
bool isFiltterrr = true ;
bool get isFiltter => isFiltterrr;
void changeStatus(bool status){
isFiltterrr = status;
notifyListeners();
}
}
this is my main.dart
class Myproject extends StatefulWidget {
const Myproject ({Key? key}) : super(key: key);
#override
_Myproject State createState() => _Myproject State();
}
class _Myproject State extends State<Myproject > {
#override
Widget build(BuildContext context) {
return
Provider(
create: (BuildContext context) {
return ProviderForFiltter();
},
child: const MaterialApp(
debugShowCheckedModeBanner: false,
home: WelcomeScreen()
),
),
);
}
}
this is my Stful Widget
ProviderForFiltter? isF ;
#override
void initState() {
super.initState();
// i tried this but it always give me errors that is isF null value
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
isF = context.read<ProviderForFiltter>();
});
// also itried this but it don't work
isF = Provider.of<ProviderForFiltter>(context, listen: false);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Text('change'),
)
}
}
in the fact i need to use it's bool value as condition into Consumer and change it
i hope any help guys
is better don't do use Provider in initState, but you can use Future.delayed
because you need context
#override
void initState() {
super.initState();
// i tried this but it always give me errors that is isF null value
Future.delayed(Duration(seconds: 1), () {
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
isF = context.read<ProviderForFiltter>();
});
// also itried this but it don't work
isF = Provider.of<ProviderForFiltter>(context, listen: false);
});
}
providers need context, in order to access it for one time you should override didChangeDependencies
#override
void didChangeDependencies() {
super.didChangeDependencies();
///access provider here and update your state if needed,
///this will be called one time just before the build method
**isF = Provider.of<ProviderForFiltter>(context, listen: false);**
}
There are multiple ways to deal with this.
The first option which I use is to add a Post Frame Callback like so:
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
aProvider = Provider.of< aProvider >(context, listen: false);
});
Alternatively, you could override the didChangeDependencies method to get the provider value once initState has been called - remembering to set the listen value to false.
I was facing the same issue and regarding the documentation of provider this should be the answer.
"This likely happens because you are modifying the ChangeNotifier from
one of its descendants while the widget tree is building."
In my case i am calling an http api async where the future is stored inside the notifier. So i have to update like this and it is working.
initState() {
super.initState();
Future.microtask(() =>
context.read<MyNotifier>().fetchSomething(someValue);
);
}
The best way is to use like this (when there's no "external parameter".
class MyNotifier with ChangeNotifier {
MyNotifier() {
_fetchSomething();
}
Future<void> _fetchSomething() async {}
}
source : https://pub.dev/packages/provider
You can use a different method called didChangeDependencies to get the value from the provider after the initState method is called. Also, make sure to set the listen value to false.
#override
void didChangeDependencies() {
super.didChangeDependencies();
final filtterData = Provider.of<ProviderForFiltter>(context, listen: false);
}

i have two blocs that must listen to each other, how do i pass one as a parameter to the other?

**Hello I am new to flutter and bloc architecture.
I am trying to build a simple quiz app that has a timer.
On the quiz page, I have two blocs, a counter cubit to navigate to the next question, and a triviabloc for quiz activities like answer selection.
I am using MultiBlovProvider to provide the blocs.
I need each bloc to communicate with each other. Since each of the blocs is a parameter to the other, how do I pass it in the multiblocprovider
?**
var bloc = TriviaBloc();
var con = CountDownController();
// ignore: close_sinks
var cubit = CounterCubit(
bloc: bloc, controller: con);
return MultiBlocProvider(
providers: [
BlocProvider<TriviaBloc>(
create: (context) => bloc,
),
BlocProvider<CounterCubit>(
create: (context) => cubit)
],
child:
QuestionScreen(trivia: questions),
);
the cubit
class CounterCubit extends Cubit<int> {
StreamSubscription sub;
CounterCubit({this.controller, this.bloc}) : super(0) {
sub = bloc.listen((state) {
if (state is AnswerCorrect || state is AnswerNotCorrect) {
controller.pause();
}
});
}
final TriviaBloc bloc;
final CountDownController controller;
void increment() => emit(state + 1);
#override
Future<void> close() {
sub?.cancel();
return super.close();
}
#override
void onChange(Change<int> change) {
print(change);
super.onChange(change);
}
}
the bloc that must listen to the cubit
class TriviaBloc extends Bloc<TriviaEvent, TriviaState> {
StreamSubscription sub;
TriviaBloc({this.cubit}) : super(TriviaInitial()) {
sub = cubit.listen(
(state) async* {
if (state != 0) {
yield TriviaInitial();
}
},
);
}
final CounterCubit cubit;
Stream<TriviaState> mapEventToState(TriviaEvent event) async* {
if (event is AnswerCLicked) {
print(event.answer);
if (event.answer == event.correctAnswer) {
yield AnswerCorrect();
} else {
yield AnswerNotCorrect();
}
}
if (event is NoAnswerChosen) {
yield ShowAnswer();
}
}
#override
Future<void> close() {
sub?.cancel();
return super.close();
}
}
Thank you
You pass one bloc as an argument to a 2nd bloc. Now, within the 2nd bloc, you can get values from the 1st bloc's state. This is an approach for that:
if (userBloc.state is AppSettled) {
achievements = (userBloc.state as AppSettled).achievements;
userBloc is the bloc that I passed to the 2nd bloc, AppSettled is a state of userBloc, and achievements is a variable defined within that state.
In order to pass data back, you can this answer
Not sure if this is what you are looking for, but this is what I do to make sure that if the user authorization state changes they JobListCubit actually triggers a route to authorization screen.
In my main.dart:
MultiBlocProvider(
providers: [
BlocProvider<UserAuthCubit>(
lazy: true,
create: (context) => UserAuthCubit(
UserAuthRepository(),
),
),
BlocProvider<JobListCubit>(
lazy: true,
create: (context) => JobListCubit(
jobListRepository: JobListRepository(),
userAuthCubit: BlocProvider.of<UserAuthCubit>(context),
)),
....
Then in my JobListCubit:
class JobListCubit extends Cubit<JobListState>
with HydratedMixin<JobListState> {
JobListState get initialState {
return initialState ?? JobListInitial();
}
final JobListRepository jobListRepository;
final UserAuthCubit userAuthCubit;
JobListCubit({this.jobListRepository, this.userAuthCubit})
: super(JobListInitial());
...
Hope this is what you were looking for. I am a novice and it took me a lot of time to find a solution...

How to reload the page whenever the page is on screen - flutter

Is there any callbacks available in flutter for every time the page is visible on screen? in ios there are some delegate methods like viewWillAppear, viewDidAppear, viewDidload.
I would like to call a API call whenever the particular page is on-screen.
Note: I am not asking the app states like foreground, backround, pause, resume.
Thank You!
Specifically to your question:
Use initState but note that you cannot use async call in initState because it calls before initializing the widget as the name means. If you want to do something after UI is created didChangeDependencies is great. But never use build() without using FutureBuilder or StreamBuilder
Simple example to demostrate:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MaterialApp(home: ExampleScreen()));
}
class ExampleScreen extends StatefulWidget {
ExampleScreen({Key key}) : super(key: key);
#override
_ExampleScreenState createState() => _ExampleScreenState();
}
class _ExampleScreenState extends State<ExampleScreen> {
List data = [];
bool isLoading = true;
void fetchData() async {
final res = await http.get("https://jsonplaceholder.typicode.com/users");
data = json.decode(res.body);
setState(() => isLoading = false);
}
// this method invokes only when new route push to navigator
#override
void initState() {
super.initState();
fetchData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: isLoading
? CircularProgressIndicator()
: Text(data?.toString() ?? ""),
),
);
}
}
Some lifecycle method of StatefulWidget's State class:
initState():
Describes the part of the user interface represented by this widget.
The framework calls this method in a number of different situations:
After calling initState.
After calling didUpdateWidget.
After receiving a call to setState.
After a dependency of this State object changes (e.g., an InheritedWidget referenced by the previous build changes).
After calling deactivate and then reinserting the State object into the tree at another location.
The framework replaces the subtree below this widget with the widget
returned by this method, either by updating the existing subtree or by
removing the subtree and inflating a new subtree, depending on whether
the widget returned by this method can update the root of the existing
subtree, as determined by calling Widget.canUpdate.
Read more
didChangeDependencies():
Called when a dependency of this State object changes.
For example, if the previous call to build referenced an
InheritedWidget that later changed, the framework would call this
method to notify this object about the change.
This method is also called immediately after initState. It is safe to
call BuildContext.dependOnInheritedWidgetOfExactType from this method.
Read more
build() (Stateless Widget)
Describes the part of the user interface represented by this widget.
The framework calls this method when this widget is inserted into the
tree in a given BuildContext and when the dependencies of this widget
change (e.g., an InheritedWidget referenced by this widget changes).
Read more
didUpdateWidget(Widget oldWidget):
Called whenever the widget configuration changes.
If the parent widget rebuilds and request that this location in the
tree update to display a new widget with the same runtimeType and
Widget.key, the framework will update the widget property of this
State object to refer to the new widget and then call this method with
the previous widget as an argument.
Read more
Some widgets are stateless and some are stateful. If it's a stateless widget, then only values can change but UI changes won't render.
Same way for the stateful widget, it will change for both as value as well as UI.
Now, will look into methods.
initState(): This is the first method called when the widget is created but after constructor call.
#override
void initState() {
// TODO: implement initState
super.initState();
}
didChangeDependecies() - Called when a dependency of this State object changes.Gets called immediately after initState method.
#override
void didChangeDependencies() {
super.didChangeDependencies();
}
didUpdateWidget() - It gets called whenever widget configurations gets changed. Framework always calls build after didUpdateWidget
#override
void didUpdateWidget (
covariant Scaffold oldWidget
)
setState() - Whenever internal state of State object wants to change, need to call it inside setState method.
setState(() {});
dispose() - Called when this object is removed from the tree permanently.
#override
void dispose() {
// TODO: implement dispose
super.dispose();
}
You don't need StatefulWidget for calling the api everytime the screen is shown.
In the following example code, press the floating action button to navigate to api calling screen, go back using back arrow, press the floating action button again to navigate to api page.
Everytime you visit this page api will be called automatically.
import 'dart:async';
import 'package:flutter/material.dart';
main() => runApp(MaterialApp(home: HomePage()));
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => ApiCaller())),
),
);
}
}
class ApiCaller extends StatelessWidget {
static int counter = 0;
Future<String> apiCallLogic() async {
print("Api Called ${++counter} time(s)");
await Future.delayed(Duration(seconds: 2));
return Future.value("Hello World");
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Api Call Count: $counter'),
),
body: FutureBuilder(
future: apiCallLogic(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) return const CircularProgressIndicator();
if (snapshot.hasData)
return Text('${snapshot.data}');
else
return const Text('Some error happened');
},
),
);
}
}
This is the simple code with zero boiler-plate.
The simplest way is to use need_resume
1.Add this to your package's pubspec.yaml file:
dependencies:
need_resume: ^1.0.4
2.create your state class for the stateful widget using type ResumableState instead of State
class HomeScreen extends StatefulWidget {
#override
HomeScreenState createState() => HomeScreenState();
}
class HomeScreenState extends ResumableState<HomeScreen> {
#override
void onReady() {
// Implement your code inside here
print('HomeScreen is ready!');
}
#override
void onResume() {
// Implement your code inside here
print('HomeScreen is resumed!');
}
#override
void onPause() {
// Implement your code inside here
print('HomeScreen is paused!');
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
child: Text('Go to Another Screen'),
onPressed: () {
print("hi");
},
),
),
);
}
}
If you want to make an API call, then you must be (or really should be) using a StatefulWidget.
Walk through it, let's say your stateful widget receives some id that it needs to make an API call.
Every time your widget receives a new id (including the first time) then you need to make a new API call with that id.
So use didUpdateWidget to check to see if the id changed and, if it did (like it does when the widget appears because the old id will be null) then make a new API call (set the appropriate loading and error states, too!)
class MyWidget extends StatefulWidget {
Suggestions({Key key, this.someId}) : super(key: key);
String someId
#override
State<StatefulWidget> createState() => MyWidgetState();
}
class MyWidgetState extends State<MyWidget> {
dynamic data;
Error err;
bool loading;
#override
Widget build(BuildContext context) {
if(loading) return Loader();
if(err) return SomeErrorMessage(err);
return SomeOtherStateLessWidget(data);
}
#override
void didUpdateWidget(covariant MyWidget oldWidget) {
super.didUpdateWidget(oldWidget);
// id changed in the widget, I need to make a new API call
if(oldWidget.id != widget.id) update();
}
update() async {
// set loading and reset error
setState(() => {
loading = true,
err = null
});
try {
// make the call
someData = await apiCall(widget.id);
// set the state
setState(() => data = someData)
} catch(e) {
// oops an error happened
setState(() => err = e)
}
// now we're not loading anymore
setState(() => loading = false);
}
}
I'm brand new to Flutter (literally, just started playing with it this weekend), but it essentially duplicates React paradigms, if that helps you at all.
Personal preference, I vastly prefer this method rather than use FutureBuilder (right now, like I said, I'm brand new). The logic is just easier to reason about (for me).

setState() called after dispose()

When I click the raised button, the timepicker is showing up. Now, if I wait 5 seconds, for example, and then confirm the time, this error will occur:
setState() called after dispose()
I literally see in the console how flutter is updating the parent widgets, but why? I don't do anything - I just wait 5 seconds?!
The example below will work in a normal project, however in my project which is quite more complex it won't work because Flutter is updating the states while I am waiting... What am I doing wrong? Does anyone have a guess at what it could be that Flutter is updating randomly in my more complex project and not in a simple project?
[UPDATE]
I took a second look at it and found out it is updating from the level on where my TabBar and TabBarView are.
Could it have to do something with the "with TickerProviderStateMixin" which I need for the TabBarView? Could it be that it causes the app to refresh regularly and randomly?
class DateTimeButton extends State<DateTimeButtonWidget> {
DateTime selectedDate = new DateTime.now();
Future initTimePicker() async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: new TimeOfDay(hour: selectedDate.hour, minute: selectedDate.minute),
);
if (picked != null) {
setState(() {
selectedDate = new DateTime(selectedDate.year, selectedDate.month, selectedDate.day, picked.hour, picked.minute);
});
}
}
#override
Widget build(BuildContext context) {
return new RaisedButton(
child: new Text("${selectedDate.hour} ${selectedDate.minute}"),
onPressed: () {
initTimePicker();
}
);
}
}
Just check boolean property mounted of the state class of your widget before calling setState().
if (this.mounted) {
setState(() {
// Your state change code goes here
});
}
Or even more clean approach
Override setState method in your StatelfulWidget class.
class DateTimeButton extends StatefulWidget {
#override
void setState(fn) {
if(mounted) {
super.setState(fn);
}
}
}
If it is an expected behavior that the Future completes when the widget already got disposed you can use
if (mounted) {
setState(() {
selectedDate = new DateTime(selectedDate.year, selectedDate.month, selectedDate.day, picked.hour, picked.minute);
});
}
Just write one line before setState()
if (!mounted) return;
and then
setState(() {
//Your code
});
I had the same problem and i solved changing the super constructor call order on initState():
Wrong code:
#override
void initState() {
foo_bar(); // call setState();
super.initState(); // then foo_bar()
}
Right code:
#override
void initState() {
super.initState();
foo_bar(); // first call super constructor then foo_bar that contains setState() call
}
To prevent the error from occurring, one can make use of the mounted property of the State class to ensure that a widget is mounted before settings its state:
// First Update data
if (!mounted) {
return;
}
setState(() { }
Try this
Widget build(BuildContext context) {
return new RaisedButton(
child: new Text("${selectedDate.hour} ${selectedDate.minute}"),
onPressed: () async {
await initTimePicker();
}
);
}
class MountedState<T extends StatefulWidget> extends State<T> {
#override
Widget build(BuildContext context) {
return null;
}
#override
void setState(VoidCallback fn) {
if (mounted) {
super.setState(fn);
}
}
}
Example
To prevent the error,Instead of using State use MountedState
class ExampleStatefulWidget extends StatefulWidget {
const ExampleStatefulWidget({Key key}) : super(key: key);
#override
_ExampleStatefulWidgetState createState() => _ExampleStatefulWidgetState();
}
class _ExampleStatefulWidgetState extends MountedState<ExampleStatefulWidget> {
....
}
I had this error when I mistakenly called super.initState before the variable. Check this:
#override
void initState() {
super.initState();
bloc = MainBloc();
}
Should be fixed as
#override
void initState() {
bloc = MainBloc();
super.initState();
}
The problem could occur when you have long asynchronous operation in stateful widget that could be closed/disposed before the operation finished.
Futures in Dart are not preemptive, so the only way is to check if a widget mounted before calling setState.
If you have a lot of widgets with asynchrony, adding ton of if (mounted) checks is tedious and an extension method might be useful
extension FlutterStateExt<T extends StatefulWidget> on State<T> {
void setStateIfMounted(VoidCallback fn) {
if (mounted) {
// ignore: invalid_use_of_protected_member
setState(fn);
}
}
}