I'm building a client for a website where users can post comments in a tree-like fashion. Currently, I'm using the following in order to display a loading bar until the comments are loaded.
FutureBuilder(
future: fetchComments(this.storyId),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.active:
case ConnectionState.waiting:
return LinearProgressIndicator();
case ConnectionState.done:
if (snapshot.hasError) {
final MissingRequiredKeysException myError = snapshot.error;
return Text('Error: ${myError.missingKeys}');
} else {
final api.Comment comment = snapshot.data;
return Expanded(child: Comment(comment.comments));
}
}
}
)
This works pretty well when there are around 200 comments, but when there are more than this the loading bar "hangs" for a noticeable amount of time.
I assume that building the Comment widget takes a significant amount of time since it can be deeply nested.
In order to avoid hanging the main thread, I've modified my code to do the widget creation inside an Isolate:
FutureBuilder(
future: compute<int, Widget>(
buildComments, this.storyId),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.active:
case ConnectionState.waiting:
return LinearProgressIndicator();
case ConnectionState.done:
if (snapshot.hasError) {
final ArgumentError myError = snapshot.error;
return Text('Error: ${myError.message}');
} else {
final Widget comments = snapshot.data;
return comments;
}
}
},
)
But this is even slower, the UI is blocked for twice the amount of time. I suspect that it might be caused by the data transfer between the isolate and the main isolate (which might happen in the main thread).
What would be a good way to solve this hanging issue?
I would like to make it as transparent as possible for the user (no loading animation when scrolling the list).
I suppose it is working slowly because you load a lot of objects into memory. I suggest you make lazy loading of comments from firebase. First show user only first 20 comments and when he scrolls to the bottom show 20 more comments and so on.
may i suggest that you dont use future builder and get 200 comments per request , as i am sure as you said parsing the data is main reason of hanging as after the async download is finished what happens is you try to parse the data which happens on main queue -not main thread- as flutter is single threaded , so can you show us how you parse the data.
Related
I have a submission form for my app where I have some data the user fills out in a form. I need to GET from an external API in the process, and use that data to create an entry in the database. All this happens once a Submit button is pressed, then after that I want to be able to go back to my homepage route.
I'm not sure how to get data from a Future function without using FutureBuilder, even though I don't need to build a widget, I just need the data.
This is what I have currently:
_populateDB() {
return new FutureBuilder(
future: fetchPost(latitude, longitude),
builder: (context, snapshot) {
if (snapshot.hasData) {
_createJson(snapshot.data);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomeScreen()
),
);
} else if (snapshot.hasError) {
return new Text("${snapshot.error}");
}
return new CircularProgressIndicator();
},
);
}
The _populateDB() function is being called when a button is pressed on the screen. What I would like to do is get data from fetchPost(latitude, longitude), use that data in the function _createJson(snapshot.data), and finally go back to the HomeScreen().
I haven't implemented _createJson(snapshot.data) yet, but currently when I call this method with onPressed, it does not go back to the HomeScreen(), and I'm not sure why.
You can get data from a Future function in asynchronous way or in synchronous way.
1 Asynchronous way
It's simple, you can use Native Future API from dart. The method then is a callback method that is called when your Future is completed. You can also use catchError method if your future was completed with some error.
fetchPost(latitude, longitude).then(
(fetchPostResultsData) {
if (fetchPostResultsData != null)
print (fetchPostResultsData);
} ).catchError(
(errorFromFetchPostResults){
print(errorFromFetchPostResults);
}
);
With this Approach your UI isn't blocked waiting results from network.
2 Synchronous way
You can use Dart key words async and await to keep your calls synchronized. In your case you have to transform your _populateDB method in an async method and await from fetchPost results.
_populateDB() async {
var data = await fetchPost(latitude, longitude);
// just execute next lines after fetchPost returns something.
if (data !=null ){
_createJson(snapshot.data);
//... do your things
}
else {
//... your handle way
}
}
With this approach your _populateDB function will wait the results from fetchPost blocking the UI Isolete and just after getting the results will execute the next instructions.
About Navigation if your HomeScreen is the previous the previous widget on stack you just need Navigator.pop(context) call but if there are others widgets in the Stack above of your HomeScreen is a better choice use Navigator.pushReplacement call.
This article shows in details with illustrations how the effects of Navigator methods. I hope it helps.
Use the below code snippet to solve it.
Future.delayed(const Duration(milliseconds: 0))
.then((value) => Navigator.pushNamed(context, '/routeName'));
I am using a normal bottom navigation bar with a local state containing the index of the currently selected page. When tapping on one of the nav items the tapped page is displayed:
class _HomePageState extends State<HomePage> {
int _selectedIndex = 1;
final _widgetOptions = [
Text('Index 0'),
Overview(),
Details(),
Text('Index 3'),
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: _widgetOptions.elementAt(_selectedIndex),
bottomNavigationBar: BottomNavigationBar(
...
currentIndex: _selectedIndex,
onTap: onTap: (index) => _selectedIndex = index,
),
);
}
}
How to proceed if you want to navigate from inside one page to another and update the selected index of the bottom navigation bar?
Example: Page 2 is an overview list which contains among other things the ID of the list items. If you tap an item in the list, it should be navigated to the details page (3 in bottom nav bar) displaying details for the selected item and therefore the ID of the selected item should be passed.
Navigator.of(context)... can't be used, because the individual pages are items of the nav bar and therefore not routes.
You will need a better state management way. I advise you to use BLoC pattern to manage navigation changes in this widget. I will put a simplified example here about how to do this with some comments and external reference to improvements.
// An enum to identify navigation index
enum Navigation { TEXT, OVERVIEW, DETAILS, OTHER_PAGE}
class NavigationBloc {
//BehaviorSubject is from rxdart package
final BehaviorSubject<Navigation> _navigationController
= BehaviorSubject.seeded(Navigation.TEXT);
// seeded with inital page value. I'am assuming PAGE_ONE value as initial page.
//exposing stream that notify us when navigation index has changed
Observable<Navigation> get currentNavigationIndex => _navigationController.stream;
// method to change your navigation index
// when we call this method it sends data to stream and his listener
// will be notified about it.
void changeNavigationIndex(final Navigation option) => _navigationController.sink.add(option);
void dispose() => _navigationController?.close();
}
This bloc class expose a stream output currentNavigationIndex. HomeScreen will be the listener of this output which provides info about what widget must be created and displayed on Scaffold widget body. Note that the stream starts with an initial value that is Navigation.TEXT.
Some changes are required in your HomePage. Now we're using StreamBuilder widget to create and provide a widget to body property. In some words StreamBuilder is listening a stream output from bloc and when some data is received which will be a Navigation enum value we decide what widget should be showed on body.
class _HomePageState extends State<HomePage> {
final NavigationBloc bloc = new NavigationBloc();
int _selectedIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<Navigation>(
stream: bloc.currentNavigationIndex,
builder: (context, snapshot){
_selectedIndex = snapshot.data.index;
switch(snapshot.data){
case Navigation.TEXT:
return Text('Index 0');
case Navigation.OVERVIEW:
// Here a thing... as you wanna change the page in another widget
// you pass the bloc to this new widget for it's capable to change
// navigation values as you desire.
return Overview(bloc: bloc);
//... other options bellow
case Navigation.DETAILS:
return Details(/* ... */);
}
},
),
bottomNavigationBar: BottomNavigationBar(
//...
currentIndex: _selectedIndex,
onTap: (index) => bloc.changeNavigationIndex(Navigation.values[index]),
),
);
}
#override
void dispose(){
bloc.dispose();// don't forgot this.
super.dispoe();
}
}
Since you wanna change the body widget of HomePage when you click in a specific items that are in other widget, Overview by example, then you need pass the bloc to this new widget and when you click in item you put new data into Stream that the body will be refreshed. Note that this way of send a BLoC instance to another widget is not a better way. I advise you take a look at InheritedWidget pattern. I do here in a simple way in order to not write a bigger answer which already is...
class Overview extends StatelessWidget {
final NavigationBloc bloc;
Overview({this.bloc});
#override
Widget build(BuildContext context) {
return YourWidgetsTree(
//...
// assuming that when you tap on an specific item yout go to Details page.
InSomeWidget(
onTap: () => bloc.changeNavigationIndex(Navigation.DETAILS);
),
);
}
}
I know so much code it's a complex way to do this but it's the way. setState calls will not solve all your needs. Take a look at this article It's one of the best and the bigger ones that talks about everything that I wrote here with minimum details.
Good Luck!
You can use Provider to manage the index of the BottomNavigationBar.
Make a class to handle the indexPage and consume it in your widgets using the Consumer. Don't forget to register the ChangeNotifierProvider in the
ChangeNotifierProvider<NavigationModel> (create: (context) => NavigationModel(),),
class NavigationModel extends ChangeNotifier {
int _pageIndex = 0;
int get page => _pageIndex;
changePage(int i) {
_pageIndex = i;
notifyListeners();
}
}
make some change like..
int _currentIndex = 0;
void onTabTapped(int index) {
setState(() {
_currentIndex = index;
});
}
body: _widgetOptions[_currentIndex],
tab click..
onTap: onTabTapped,
I'm creating a page that has a TextField, when user enters 3+ char in it I fetch rows, from a database, that contain the inserted text. In the example I provide I simulate this by getting a List. After this a list is presented to the user, the user can tap one of the rows to go to another page.
gist example
My problem is that when I tap a row MaterialPageRoute WidgetBuilder runs twice, this is the log:
---------- onTap ----------
---------- MaterialPageRoute ----------
---------- SecondPage build ----------
---------- MaterialPageRoute ----------
---------- SecondPage build ----------
Can someone explain this behavior and also how to fix it?
Thanks.
I have faced the same problem. This is because you didn't add any condition to FutureBuilder. So when you are using setState() it gets called for the next time.
You can solve it using a flag in Future function so that it is invoked for the first time only. Eg:
bool flag = true;
flag?FutureBuilder(
future: getData(),
builder: (BuildContext context, AsyncSnapshot snap){
if(snap.connectionState != ConnectionState.done){
return Center(child: CircularProgressIndicator(),);
}else{
return populate();
}
},
):Container();
Future getData()async{
flag = false;
return await fetchFromDatabase();
}
Is it possible to preload somehow the image on the app start? Like I have an background image in my drawer but for the first time when I open the drawer I can see the image blinks like it is fetched from assets and then displayed and it gives bad experience to me once I see it for the first time other openings of the drawer are behaving as expected because it is cached. I would like to prefetch it on the app load so there is no such effect.
Use the precacheImage function to start loading an image before your drawer is built. For example, in the widget that contains your drawer:
class MyWidgetState extends State<MyWidget> {
#override
void initState() {
// Adjust the provider based on the image type
precacheImage(new AssetImage('...'));
super.initState();
}
}
I had problems with the upper solution which uses precacheImage() inside initState. The code below resolved them. Also note that you might not see expected results in the debug mode but only in the release mode.
Image myImage;
#override
void initState() {
super.initState();
myImage= Image.asset(path);
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
precacheImage(myImage.image, context);
}
There is a good article on this subject : https://alex.domenici.net/archive/preload-images-in-a-stateful-widget-on-flutter
It should look something like this
class _SampleWidgetState extends State<SampleWidget> {
Image image1;
Image image2;
Image image3;
Image image4;
#override
void initState() {
super.initState();
image1 = Image.asset("assets/image1.png");
image2 = Image.asset("assets/image2.png");
image3 = Image.asset("assets/image3.png");
image4 = Image.asset("assets/image4.png");
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
precacheImage(image1.image, context);
precacheImage(image2.image, context);
precacheImage(image3.image, context);
precacheImage(image4.image, context);
}
#override
Widget build(BuildContext context) {
return Container(
child: Stack(
children: <Widget>[
image1,
image2,
image3,
image4,
],
),
);
}
}
To get rid of the "blink", you can simply use the FadeInImage class in combination with transparent_image, which will fade instead of appearing instantly. Usage, in your case, looks as follow:
// you need to add transparent_image to your pubspec and import it
// as it is required to have the actual image fade in from nothing
import 'package:transparent_image/transparent_image.dart';
import 'package:flutter/material.dart';
...
FadeInImage(
placeholder: MemoryImage(kTransparentImage),
image: AssetImage('image.png'),
)
The precacheImage() function (as used in most of the answers) returns a Future, and for certain use case scenarios it can be really useful. For instance, in my app I needed to load an external image and like everyone else did not want to experience the flickering. So I ended up with something like this:
// show some sort of loading indicator
...
precacheImage(
NetworkImage(),
context,
).then((_) {
// replace the loading indicator and show the image
// (may be with some soothing fade in effect etc.)
...
});
Please note that, in the above example I wanted to illustrate how the Future can be potentially used. The comments are just to help express the idea. Actual implementation has to be done in a Fluttery way.
I had the following problem: image requires some space. So after loading, it pushed UI down which is not good for UX. I decided to create a builder to display an empty (or loading) container until the image is loaded and after that display my UI.
Looks like precacheImage returns future which is resolved. The tricky part for me was FutureBuilder and snapshot.hasData which was always false because future is resolved with null. So I added future transformation to fix snapshot.hasData:
precacheImage(this.widget.imageProvider, context).then((value) => true)
I'm not sure is it ok to call precacheImage multiple times so I decided to wrap it into StatefulWidget.
You can check the final builder here
Use builder the following way:
return PreloadingImageBuilder(
imageProvider: AssetImage("assets/images/logo-main.png"),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Scaffold(
...
);
} else {
return Container();
}
},
);
Depending on your logic and UX, something like this can work too (when pushing a new route with images):
Future.wait([
precacheImage(AssetImage("assets/imageA.png"), context),
]).then((value) {
Navigator.pop(context);
Navigator.pushReplacement(
context,
YourRouteRoute()
);
});
late AssetImage assetImage;
#override
void initState() {
assetImage = const AssetImage("$kImagePath/bkg2.png");
super.initState();
}
#override
void didChangeDependencies() {
precacheImage(assetImage, context);
super.didChangeDependencies();
}
My question is about navigation used with the BLoC pattern.
In my LoginScreen widget I have a button that adds an event into the EventSink of the bloc. The bloc calls the API and authenticates the user.
Where in the LoginScreen Widget do I have to listen to the stream, and how do I navigate to another screen after it returns a success status?
Use BlockListener.
BlocListener(
bloc: _yourBloc,
listener: (BuildContext context, YourState state) {
if(state is NavigateToSecondScreen){
Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) {return SecondScreen();}));
}
},
child: childWidget
)
The navigator is not working in blocBuilder, because in blocBuilder, you can only return a widget
But BlocListener solved it for me.
Add this code:
BlocListener(
bloc: _yourBloc,
listener: (BuildContext context, YourState state) {
if(state is NavigateToSecondScreen){
Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) {return SecondScreen();}));
}
},
child: childWidget
)
First of all: if there isn't any business logic, then there isn't any need to go to YourBloc class.
But from time to time some user's activity is required to perform some logic in Bloc class and then the Bloc class has to decide what to do next: just rebuild widgets or show dialog or even navigate to next route. In such a case, you have to send some State to UI to finish the action.
Then another problem appears: what shall I do with widgets when Bloc sends State to show a toast?
And this is the main issue with all of this story.
A lot of answers and articles recommend to use flutter_block. This library has BlocBuilder and BlocListener. With those classes you can solve some issues, but not 100% of them.
In my case I used BlocConsumer which manages BlocBuilder and BlocListener and provides a brilliant way to manage states.
From the documentation:
BlocConsumer<BlocA, BlocAState>(
listenWhen: (previous, current) {
// Return true/false to determine whether or not
// to invoke listener with state
},
listener: (context, state) {
// Do stuff here based on BlocA's state
},
buildWhen: (previous, current) {
// Return true/false to determine whether or not
// to rebuild the widget with state
},
builder: (context, state) {
// Return widget here based on BlocA's state
}
)
As you can see with BlocConsumer, you can filter states: you can easily define states to rebuild widgets and states to show some popups or navigate to the next screen.
Something like this:
if (state is PhoneLoginCodeSent) {
// Dispatch here to reset PhoneLoginFormState
SchedulerBinding.instance.addPostFrameCallback((_) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return VerifyCodeForm(phoneLoginBloc: _phoneLoginBloc);
},
),
);
return;
});
}