Navigate while Widget state build is being executed - flutter

I'm building a simple Flutter app. Its launch screen determines if the user if logged in or not, and depending on that redirects to the login or main/home screen afterwards.
My Launch screen is a StatefulWidget, its state is shown below. It uses a ViewModel class that extends ChangeNotifier (its code is irrelevant, so I didn't include it).
class _LaunchPageState extends State<LaunchPage> {
LaunchViewModel _viewModel = LaunchViewModel();
#override
void initState() {
super.initState();
_viewModel.checkSessionStatus();
}
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<LaunchViewModel>(
builder: (_) => _viewModel,
child: Scaffold(
body: Consumer<LaunchViewModel>(
builder: (context, viewModel, _) {
if (viewModel.state is LaunchInitial) {
return CircularProgressIndicator();
}
if (viewModel.state is LaunchLoginPage) {
Navigator.pushNamed(context, "login");
}
if (viewModel.state is LaunchMainPage) {
Navigator.pushNamed(context, "main");
}
return Container();
},
),
),
);
}
}
The ViewModel emits one of 3 states:
LaunchInitial: Default state.
LaunchLoginPage: Indicates that the Login page should be displayed.
LaunchMainPage: Indicates that the Main page should be displayed.
The LaunchInitial state is handled fine, and a progress bar is displayed on the screen. But the other 2 states cause the app to crash. The following error is thrown:
This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets
It seems that trying to redirect to another screen while the Consumer's build method is being executed is causing this issue. What's the correct way to do this?
Thanks!

You can't directly call Navigator within widget tree. If you have event-state builder, so better change the widget tree you are rendering:
builder: (context, viewModel, _) {
if (viewModel.state is LaunchInitial) {
return CircularProgressIndicator();
}
if (viewModel.state is LaunchLoginPage) {
return LoginPage();
}
if (viewModel.state is LaunchMainPage) {
return MainPage();
}
return Container();
},
You have to return Widget with each child inside build method.
Alternatively, you can do this with Navigation:
#override
void didChangeDependencies() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (viewModel.state is LaunchLoginPage) {
Navigator.pushNamed(context, "login");
}
if (viewModel.state is LaunchMainPage) {
Navigator.pushNamed(context, "main");
}
});
super.didChangeDependencies();
}
addPostFrameCallback method will be called right after the build method completed and you can navigate inside.
Be sure your provider don't have lifecycle issue.

Related

Flutter - how to correctly create a button widget that has a spinner inside of it to isolate the setState call?

I have a reuable stateful widget that returns a button layout. The button text changes to a loading spinner when the network call is in progress and back to text when network request is completed.
I can pass a parameter showSpinner from outside the widget, but that requires to call setState outside of the widget, what leads to rebuilding of other widgets.
So I need to call setState from inside the button widget.
I am also passing a callback as a parameter into the button widget. Is there any way to isolate the spinner change state setting to inside of such a widget, so that it still is reusable?
The simplest and most concise solution does not require an additional library. Just use a ValueNotifier and a ValueListenableBuilder. This will also allow you to make the reusable button widget stateless and only rebuild the button's child (loading indicator/text).
In the buttons' parent instantiate the isLoading ValueNotifier and pass to your button widget's constructor.
final isLoading = ValueNotifier(false);
Then in your button widget, use a ValueListenableBuilder.
// disable the button while waiting for the network request
onPressed: isLoading.value
? null
: () async {
// updating the state is super easy!!
isLoading.value = true;
// TODO: make network request here
isLoading.value = false;
},
#override
Widget build(BuildContext context) {
return ValueListenableBuilder<bool>(
valueListenable: isLoading,
builder: (context, value, child) {
if (value) {
return CircularProgressIndicator();
} else {
return Text('Load Data');
}
},
);
}
You can use StreamBuilder to solve this problem.
First, we need to create a stream. Create a new file to store it, we'll name it banana_stream.dart, for example ;).
class BananaStream{
final _streamController = StreamController<bool>();
Stream<bool> get stream => _streamController.stream;
void dispose(){
_streamController.close();
}
void add(bool isLoading){
_streamController.sink.add(isLoading);
}
}
To access this, you should use Provider, so add a Provider as parent of the Widget that contain your reusable button.
Provider<BananaStream>(
create: (context) => BananaStream(),
dispose: (context, bloc) => bloc.dispose(),
child: YourWidget(),
),
Then add the StreamBuilder to your button widget:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamBuilder<bool>(
stream: Provider.of<BananaStream>(context, listen:false),
initialData: false,
builder: (context, snapshot){
final isLoading = snapshot.data;
if(isLoading == false){
return YourButtonWithNoSpinner();
} else{
return YourButtonWithSpinner();
}
}
);
}
}
And to change isLoading outside, you can use this code:
final provider = Provider.of<BananaStream>(context, listen:false);
provider.add(true); //here is where you change the isLoading value
That's it!
Alternatively, you can use ValueNotifier or ChangeNotifier but i find it hard to implement.
I found the perfect solution for this and it is using the bloc pattern. With this package https://pub.dev/packages/flutter_bloc
The idea is that you create a BLOC or a CUBIT class. Cubit is just a simplified version of BLOC. (BLOC = business logic component).
Then you use the bloc class with BlocBuilder that streams out a Widget depending on what input you pass into it. And that leads to rebuilding only the needed button widget and not the all tree.
simplified examples in the flutter counter app:
// input is done like this
onPressed: () {
context.read<CounterCubit>().decrement();
}
// the widget that builds a widget depending on input
_counterTextBuilder() {
return BlocBuilder<CounterCubit, CounterState>(
builder: (context, state) {
if (state.counterValue < 0){
return Text("negative value!",);
} else if (state.counterValue < 5){
return Text("OK: ${state.counterValue}",
);
} else {
return ElevatedButton(onPressed: (){}, child: const Text("RESET NOW!!!"));
}
},
);
}

Navigator.pop from a FutureBuilder

I have a first screen which ask the user to enter to input, then when the users clicks on a button, the app goes on a second screen which uses a FutureBuilder to call an API.
If the API returns an error, I would like to go back to the previous screen with Navigator.pop. When I try to do that in the builder of the FutureBuilder, I get an error because I modify the tree while I am building it...
setState() or markNeedsBuild() called during build. This Overlay
widget cannot be marked as needing to build because the framework is
already in the process of building widgets
What is the proper way to go to the previous screen if an error occur?
class Stackoverflow extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<Flight>(
future: fetchData(context),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ScreenBody(snapshot.data);
} else if (snapshot.hasError) {
Navigator.pop(context, "an error");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
)
),
);
}
}
PS: I tried to use addPostFrameCallback and use the Navigator.pop inside, but for some unknown reason, it is called multiple times
You can not directly navigate when build method is running, so it better to show some error screen and give use chance to go back to last screen.
However if you want to do so then you can use following statement to do so.
Future.microtask(() => Navigator.pop(context));
I'd prefer to convert class into StateFullWidget and get rid of FutureBuilder
class Stackoverflow extends StatefulWidget {
#override
_StackoverflowState createState() => _StackoverflowState();
}
class _StackoverflowState extends State<Stackoverflow> {
Flight flight;
#override
void initState() {
super.initState();
fetchData().then((data) {
setState(() {
flight = data;
});
}).catchError((e) {
Navigator.pop(context, "an error");
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: flight != null ? ScreenBody(flight) : CircularProgressIndicator(),
),
);
}
}
and of cause pass context somewhere outside class is not good approach

How to get data from database after event from another screen

I came from Android Development, so, I'll try to explain my situation in Android terms in some cases. So, I have the MainScreen, which uses Scaffold and has FAB. The body of this screen is another widget (as Fragment in Android). When I click on the FAB (which is on MainScreen), bottom modal is opened. By this model, I can add data to the database. But I also want to add new data to my widget (fragment) at the same time. And I don't know in which method of lifecycle I should do call to DB. In android such method is onResume, but I didn't find it's analogue in Flutter.
I'll appreciate any help, thanks in advance!
UPD
There's my screen:
Bottom navigation and FAB is on the MainScreen. ListView is on the widget, which is body of MainScreen's Scaffold. Another my step is clicking on FAB. This click opens bottom modal
When I click save on the modal, data is saved to DB and modal close. And after this closing I want to see new database entry, which I just added from the modal. Now I can see new notes only after closing and then opening screen again. Here's my code:
class NotesScreen extends StatefulWidget {
#override
_NotesScreenState createState() => _NotesScreenState();
}
class _NotesScreenState extends State<NotesScreen> with WidgetsBindingObserver {
List<Note> _notes = new List<Note>();
#override
void initState() {
super.initState();
Fimber.i("Init");
WidgetsBinding.instance.addObserver(this);
NotesDataManager().getNotes().then((value) {
_notes = value;
setState(() {
});
});
}
#override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state){
case AppLifecycleState.resumed:
NotesDataManager().getNotes().then((value){
_notes = value;
setState(() {
});
});
Fimber.i("Resumed");
break;
case AppLifecycleState.inactive:
Fimber.i("Inactive");
break;
case AppLifecycleState.paused:
Fimber.i("Paused");
break;
case AppLifecycleState.suspending:
Fimber.i("Suspending");
break;
}
super.didChangeAppLifecycleState(state);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(AppColors.layoutBackgroundColor),
body: Container(
child: ListView.builder(
itemCount: _notes.length,
itemBuilder: (BuildContext context, int index) {
return NotesListItemWidget(note: _notes[index]);
},
),
),
);
}
}
As you can see, I added WidgetsBindingObserver, but it didn't help
You might want to use state management in your app. The easiest one is Provider. Your model should extend ChangeNotifier and whenever you add a new instance of model the app will be notified: notifyListener. In build you will implement ChangeNotifierProvider. Here is some tutorials:
Provider example 1
Provider example 2
Or you can just search for Provider

Change state in one Widget from another widget

I'm programming a flutter application in which a user is presented with a PageView widget that allows him/her to navigate between 3 "pages" by swiping.
I'm following the setup used in https://medium.com/flutter-community/flutter-app-architecture-101-vanilla-scoped-model-bloc-7eff7b2baf7e, where I use a single class to load data into my model, which should reflect the corresponding state change (IsLoadingData/HasData).
I have a main page that holds all ViewPage widgets. The pages are constructed in the MainPageState object like this:
#override
void initState() {
_setBloc = SetBloc(widget._repository);
_notificationBloc = NotificationBloc(widget._repository);
leftWidget = NotificationPage(_notificationBloc);
middleWidget = SetPage(_setBloc);
currentPage = middleWidget;
super.initState();
}
If we go into the NotificationPage, then the first thing it does is attempt to load data:
NotificationPage(this._notificationBloc) {
_notificationBloc.loadNotificationData();
}
which should be reflected in the build function when a user directs the application to it:
//TODO: Consider if state management is correct
#override
Widget build(BuildContext context) {
return StreamBuilder<NotificationState>(
stream: _notificationBloc.notification.asBroadcastStream(),
//initialData might be problematic
initialData: NotificationLoadingState(),
builder: (context, snapshot) {
if (snapshot.data is NotificationLoadingState) {
return _buildLoading();
}
if (snapshot.data is NotificationDataState) {
NotificationDataState state = snapshot.data;
return buildBody(context, state.notification);
} else {
return Container();
}
},
);
}
What happens is that the screen will always hit "NotificationLoadingState" even when data has been loaded, which happens in the repository:
void loadNotificationData() {
_setStreamController.sink.add(NotificationState._notificationLoading());
_repository.getNotificationTime().then((notification) {
_setStreamController.sink
.add(NotificationState._notificationData(notification));
print(notification);
});
}
The notification is printed whilst on another page that is not the notification page.
What am i doing wrong?
//....
class _SomeState extends State<SomeWidget> {
//....
Stream<int> notificationStream;
//....
#override
void initState() {
//....
notificationStream = _notificationBloc.notification.asBroadcastStream()
super.initState();
}
//....
Widget build(BuildContext context) {
return StreamBuilder<NotificationState>(
stream: notificationStream,
//....
Save your Stream somewhere and stop initialising it every time.
I suspect that the build method is called multiple times and therefore you create a new stream (initState is called once).
Please try let me know if this helped.

Can I skip BlocBuilder render in some case?

There's a screen that have a bloc MyBloc myBloc
In the screen's build method, it's like this:
Widget build(BuildContext context) {
return MyCustomLoadingStack( //My custom widget to have the main content below the loading widget
_buildContent(context), //My main content
_buildLoading(context)); //My loading on top
}
And my 2 method:
Widget _buildContent(BuildContext context) {
return Column(children: <Widget>[
OtherWidgetOne(),
OtherWidgetTwo(),
BlocBuilder<MyEvent, MyState>(
bloc: myBloc,
builder: (BuildContext context, MyStatestate) {
switch (state.type) {
case MyStateList.doneWorking:
return MyDataWidget(); // this content cares about displaying the data only
default:
return Container(); //otherwise display nothing
}
},
)
]);
}
Widget _buildLoading(BuildContext context) {
return BlocBuilder<MyEvent, MyState>(
bloc: myBloc,
builder: (BuildContext context, MyState state) {
switch (state.type) {
case MyStateList.loading:
return LoadingView(); //This _buildLoading cares the loading only
default:
return Container(); //If it's not loading the show nothing for the loading layer
}
},
)
}
My problem is when the content is currently showing data. When I yield MyState(type: MyStateList.loading) to show the loading when doing something else (like load more for the data which is currently showing). Both BlocBuilder are called and then the _buildContent(context) show nothing because it doesn't meet the MyStateList.doneWorking condition. And of course the _buildLoading(context) shows the loading on an empty content bellow.
Is there anyway I can skip the BlocBuilder inside _buildContent(context) to keeps showing the current data and still have the loading on top?
I though about having a Widget to contains the data or empty Container() to use in the default case of the _buildContent(context) but it doesn't make sense to me because they may re-render the same widget.
Thank you for your time.
Great question! Is there a reason why you're using BlocBuilder instead of StreamBuilder?
To show nothing while the data is loading and auto populate the data once it's loaded, I typically do the following:
Widget _buildLoading(BuildContext context) {
return StreamBuilder<Model>(
stream: bloc.modelStream,
builder: (context, snapshot) {
if (snapshot.hasError) return _buildErrorWidget(snapshot.error, context);
if (snapshot.hasData) {
return DesiredWidget()
} else {
return LoadingView()
}
}
I haven't seen your BloC file but you may have to add a couple lines like the following:
final _modelFetcher = BehaviorSubject<Model>();
Stream<Model> get modelStream => _modelFetcher.stream;
Function(Model) get changeModelFetcher => _modelFetcher.sink.add;
#override
void dispose() async {
await _modelFetcher.drain();
_modelFetcher.close();
}
Let me know if this helps at all.
There is a pullrequest beeing discussed to fix this problem right now:
https://github.com/felangel/bloc/issues/315?fbclid=IwAR2x_Q1x5MIUUPE7zFRpjNkhjx5CzR0qiRx-P3IKZR_VRGEp3eqQisTthDo
For now, you can use a class for a more complex state. This can be something like:
class MyState extends Equatable {
final bool isLoading;
final List<MyData> data;
bool get hasData => data.isNotEmpty;
MyState(this.isLoading,this.data) : super([isLoading,data]);
}
I use Equatable (https://pub.dev/packages/equatable) for easier isEqual implementation.
Widget _buildContent(BuildContext context) {
return Column(children: <Widget>[
OtherWidgetOne(),
OtherWidgetTwo(),
BlocBuilder<MyEvent, MyState>(
bloc: myBloc,
builder: (BuildContext context, MyStatestate) {
if (state.hasData) {
return MyDataWidget(); // this content cares about displaying the data only
} else {
return Container(); //otherwise display nothing
}
},
)
]);
}
Widget _buildLoading(BuildContext context) {
return BlocBuilder<MyEvent, MyState>(
bloc: myBloc,
builder: (BuildContext context, MyState state) {
if (state.isLoading) {
return LoadingView(); //This _buildLoading cares the loading only
} else {
return Container(); //If it's not loading the show nothing for the loading layer
}
},
);
}
Downside of this appraoch is, that the datawidget will redraw, even tho the data doesnt change. This will be fixed with the mentioned pullrequest.