Provider: setState() or markNeedsBuild() called during build - flutter

I'm using Hive to store the whole list of Card items, related to an Extension. In the screen of the selected extension, I am displaying the Cards of this extension, with bunch of filters/sorting.
To do that, I use ValueListenableBuilder to get the current extension and their cards.
And when I filter/sort this list, I want to store them into my Provider class, because I would to reuse this list into another screen.
But we I do context.read<ShowingCardsProvider>().setAll(sortedList), I got this error:
setState() or markNeedsBuild() called during build.
I don't listen ShowingCardsProvider anywhere for now.
Can you explain to me what's wrong here?
Thank you!
main.dart
runApp(MultiProvider(
providers: [
ChangeNotifierProvider.value(value: AuthProvider()),
ChangeNotifierProvider.value(value: UserProvider()),
ChangeNotifierProvider.value(value: ShowingCardsProvider()),
],
child: MyApp(),
));
showing_cards_provider.dart
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:pokecollect/card/models/card.dart';
class CardsProvider extends ChangeNotifier {
final List<CardModel> _items = [];
UnmodifiableListView<CardModel> get items => UnmodifiableListView(_items);
void setAll(List<CardModel>? items) {
_items.clear();
if (items != null || items!.isNotEmpty) {
_items.addAll(items);
}
notifyListeners();
}
void addAll(List<CardModel> items) {
_items.addAll(items);
notifyListeners();
}
void removeAll() {
_items.clear();
notifyListeners();
}
}
extension_page.dart
#override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
body: SafeArea(
child: LayoutBuilder(builder: (context, constraints) {
return CustomScrollView(
slivers: [
SliverAppBar(
...
),
...
SliverPadding(
padding: EdgeInsets.symmetric(horizontal: 16.0),
sliver: ValueListenableBuilder(
valueListenable: ExtensionBox.box.listenable(keys: [_extensionUuid]),
builder: (ctx, Box<Extension> box, child) {
List<CardModel>? cardsList = box
.get(_uuid)!
.cards
?.where((card) => _isCardPassFilters(card))
.cast<CardModel>()
.toList();
var sortedList = _simpleSortCards(cardsList);
context.read<ShowingCardsProvider>().setAll(sortedList);
return _buildCardListGrid(sortedList);
},
),
),
]
);
}),
),
);
}

This is indeed because I'm using ValueListenableBuilder and, while the Widget is building, notifyListeners is called (into my provider).
My hotfix is to do this:
return Future.delayed(
Duration(milliseconds: 1),
() => context.read<ShowingCardsProvider>().setAll(list),
);
Not very beautiful, but it works 😅
If you have a more elegant way, fell free to comment it!

Related

Offstage Navigators rebuild

I have implemented the multiple Offstage Navigators for the bottomNavigationBar, further details can be seen here. The problem is that when using this method, each time we select a bottom navigation item, the FutureBuilder runs the future method and rebuilds the entire widget, each Offstage widget and all their children are also rebuilt.
For each Offstage widget, I'm loading data via html request and that means each time I switch a tab, 5 requests will be made.
This is my main Scaffold which holds the bottomNavigationBar.
#override
Widget build(BuildContext context) {
TabProvider tabProvider = Provider.of<TabProvider>(context);
return FutureBuilder(
future: initProvider(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
appBar: AppBar(
title: Text(tabName[tabProvider.currentTab],
),
body: Stack(children: <Widget>[
_buildOffstageNavigator(TabItem.feed, tabProvider.currentTab),
_buildOffstageNavigator(TabItem.explore, tabProvider.currentTab),
_buildOffstageNavigator(TabItem.guide, tabProvider.currentTab),
_buildOffstageNavigator(TabItem.map, tabProvider.currentTab),
_buildOffstageNavigator(TabItem.profile, tabProvider.currentTab),
]),
bottomNavigationBar: BottomNavigation(
currentTab: tabProvider.currentTab,
onSelectTab: tabProvider.selectTab,
),
),
);
} else {
return Text('Loading');
}
},
);
}
The FutureBuilder will initialize the values in my provider so each tab can access the cached data.
The _buildOffstageNavigator will return the below
return Offstage(
offstage: currentTab != tabItem,
child: TabNavigator(
navigatorKey: navigatorKeys[tabItem],
tabItem: tabItem,
),
);
Below is the Widget which is built inside the Scaffold body and hence inside the Offstage Navigator from above.
#override
Widget build(BuildContext context) {
TabProvider tabProvider = Provider.of<TabProvider>(context);
States stateData = tabProvider.exploreStateCache;
return Container(
child: ListView(
children: <Widget>[
Text(stateData.stateName),
Text(stateData.stateDescription),
],
),
);
}
I have followed this articles advice for using futures with the provider but something else is missing
Instead of creating futures in a build method, which as you have noticed, may be called several times, create them in a place that is invoked only once. For example, a StatefulWidget's initState:
class Foo extends StatefulWidget {
#override
_FooState createState() => _FooState();
}
class _FooState extends State<Foo> {
Future<MyData> _dataFuture;
#override
void initState() {
super.initState();
_dataFuture = getData();
}
#override
Widget build(BuildContext context) => FutureBuilder<MyData>(
future: _dataFuture,
builder: (context, snapshot) => ...,
);
}
A second thing you can improve is reduce the scope of what gets rebuild when the provider provides a new value for TabProvider. The context that you call Provider.of<Data>(context) gets rebuild when there's a new value for Data. That is done most conveniently with the various other widgets offered by the provider package, like Consumer and Selector.
So remove the Provider<TabProvder>.of(context) calls and use Consumers and Selectors. For example, to only rebuild the title when a tab is switched:
AppBar(
title: Selector<TabProvider, String>(
selector: (context, tabProvider) => tabName[tabProvider.currentTab],
builder: (context, title) => Text(title),
),
)
Selector only rebuilds the Text(title) widget, when the result of its selector callback is different from the previous value. Similarly for _buildOffstageNavigator:
Widget _buildOffstageNavigator(BuildContext context, TabItem tabItem) {
return Selector<TabProvider, bool>(
selector: (context, tabProvider) => tabProvider.currentTab != tabItem,
builder: (context, isCurrent) => Offstage(
offstage: isCurrent,
child: Selector<TabProvider, Key>(
selector: (context, tabProvider) => tabProvider.navigatorKeys[tabItem],
builder: (context, tabKey) => TabNavigator(
navigatorKey: tabKey,
tabItem: tabItem,
),
),
);
}
(Beware: All code is untested and contains typos)

How to properly initialize a Future in Flutter Provider

so I am trying to build up a list in my provider from a Future Call.
So far, I have the following ChangeNotifier class below:
class MainProvider extends ChangeNotifier {
List<dynamic> _list = <dynamic>[];
List<dynamic> get list => _list;
int count = 0;
MainProvider() {
initList();
}
initList() async {
var db = new DatabaseHelper();
addToList(Consumer<MainProvider>(
builder: (_, provider, __) => Text(provider.count.toString())));
await db.readFromDatabase(1).then((result) {
result.forEach((item) {
ModeItem _modelItem= ModeItem.map(item);
addToList(_modelItem);
});
});
}
addToList(Object object) {
_list.add(object);
notifyListeners();
}
addCount() {
count += 1;
notifyListeners();
}
}
However, this is what happens whenever I use the list value:
I can confirm that my initList function is executing properly
The initial content from the list value that is available is the
Text() widget that I firstly inserted through the addToList function, meaning it appears that there is only one item in the list at this point
When I perform Hot Reload, the rest of the contents of the list seems to appear now
Notes:
I use the value of list in a AnimatedList widget, so I am
supposed to show the contents of list
What appears initially is that the content of my list value is only one item
My list value doesn't seem to automatically update during the
execution of my Future call
However, when I try to call the addCount function, it normally
updates the value of count without needing to perform Hot Reload -
this one seems to function properly
It appears that the Future call is not properly updating the
contents of my list value
My actual concern is that on initial loading, my list value doesn't
properly initialize all it's values as intended
Hoping you guys can help me on this one. Thank you.
UPDATE: Below shows how I use the ChangeNotifierClass above
class ParentProvider extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<MainProvider>(
create: (context) => MainProvider(),
),
],
child: ParentWidget(),
);
}
}
class ParentWidget extends StatelessWidget {
final GlobalKey<AnimatedListState> listKey = GlobalKey<AnimatedListState>();
#override
Widget build(BuildContext context) {
var mainProvider = Provider.of<MainProvider>(context);
buildItem(BuildContext context, int index, Animation animation) {
print('buildItem');
var _object = mainProvider.list[index];
var _widget;
if (_object is Widget) {
_widget = _object;
} else if (_object is ModelItem) {
_widget = Text(_object.unitNumber.toString());
}
return SizeTransition(
key: ValueKey<int>(index),
axis: Axis.vertical,
sizeFactor: animation,
child: InkWell(
onTap: () {
listKey.currentState.removeItem(index,
(context, animation) => buildItem(context, index, animation),
duration: const Duration(milliseconds: 300));
mainProvider.list.removeAt(index);
mainProvider.addCount();
},
child: Card(
child: Padding(
padding: const EdgeInsets.all(32.0),
child: _widget,
),
),
),
);
}
return Scaffold(
appBar: AppBar(),
body: Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(32.0),
child: mainProvider.list == null
? Container()
: AnimatedList(
key: listKey,
initialItemCount: mainProvider.list.length,
itemBuilder:
(BuildContext context, int index, Animation animation) =>
buildItem(context, index, animation),
),
),
),
);
}
}
You are retrieving your provider from a StatelessWidget. As such, the ChangeNotifier can't trigger your widget to rebuild because there is no state to rebuild. You have to either convert ParentWidget to be a StatefulWidget or you need to get your provider using Consumer instead of Provider.of:
class ParentWidget extends StatelessWidget {
final GlobalKey<AnimatedListState> listKey = GlobalKey<AnimatedListState>();
#override
Widget build(BuildContext context) {
return Consumer<MainProvider>(
builder: (BuildContext context, MainProvider mainProvider, _) {
...
}
);
}
As an aside, the way you are using provider is to add the MainProvider to its provider and then retrieve it from within its immediate child. If this is the only place you are retrieving the MainProvider, this makes the provider pattern redundant as you can easily just declare it within ParentWidget, or even just get your list of images using a FutureBuilder. Using provider is a good step toward proper state management, but also be careful of over-engineering your app.

Flutter FutureBuilder refresh when TextField value changes

The _futureData is to used for the FutureBuilder after retrieving value from the _loadPhobias() function.
entry_screen.dart
Future _futureData;
final TextEditingController _textEditingController = TextEditingController();
_loadPhobias() function does not seem to have any problem.
entry_screen.dart
Future<List<String>> _loadPhobias() async =>
await rootBundle.loadString('assets/phobias.txt').then((phobias) {
List _listOfAllPhobias = [];
List<String> _listOfSortedPhobias = [];
_textEditingController.addListener(() {
...
});
return _listOfSortedPhobias;
});
#override
void initState() {
super.initState();
_futureData = _loadPhobias();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: TextField(
// When the value is changed, the value returned from the _loadPhobias will also change. So I want the FutureBuilder to be rebuilt.
onChanged: (text) { setState(() => _futureData = _loadPhobias()) },
),
),
body: FutureBuilder(
future: _futureData,
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) => Column(
children: <Widget>[
PhobiasCard(sentence: snapshot.data[index]),
)
],
))
: Center(
child: CircularProgressIndicator(),
);
},
),
),
);
}
This is the error that I got:
FlutterError (setState() callback argument returned a Future.
The setState() method on _EntryScreenState#51168 was called with a closure or method that returned a Future. Maybe it is marked as "async".
Instead of performing asynchronous work inside a call to setState(), first execute the work (without updating the widget state), and then synchronously update the state inside a call to setState().)
The first thing to note, you mentioned that you want to rebuild your app every time there's a change in the text. For that to happen, you should use StreamBuilder instead. FutureBuilder is meant to be consumed once, it's like a fire and forget event or Promise in JavaScript.
Here's to a good comparison betweenStreamBuilder vs FutureBuilder.
This is how you would refactor your code to use StreamBuilder.
main.dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyAppScreen(),
);
}
}
class MyAppScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return MyAppScreenState();
}
}
class MyAppScreenState extends State<MyAppScreen> {
StreamController<List<String>> _phobiasStream;
final TextEditingController _textEditingController = TextEditingController();
void _loadPhobias() async =>
await rootBundle.loadString('lib/phobia.txt').then((phobias) {
List<String> _listOfSortedPhobias = [];
for (String i in LineSplitter().convert(phobias)) {
for (String t in _textEditingController.text.split('')) {
if (i.split('-').first.toString().contains(t)) {
_listOfSortedPhobias.add(i);
}
}
}
_phobiasStream.add(_listOfSortedPhobias);
});
#override
void initState() {
super.initState();
_phobiasStream = StreamController<List<String>>();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: TextField(
controller: _textEditingController,
onChanged: (text) {
print("Text $text");
_loadPhobias();
},
),
),
body: StreamBuilder(
stream: _phobiasStream.stream,
builder: (context, snapshot) {
return snapshot.hasData
? Container(
height: 300,
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
print("Data ${snapshot.data[index]}");
return Text(snapshot.data[index]);
},
),
)
: Center(
child: CircularProgressIndicator(),
);
},
),
);
}
}
As seen in the code above, I eliminated unnecessary text change callbacks inside the for a loop.
lib/phobia.txt
test1-test2-test3-test4-test5
Let me know if this is the expected scenario.
Hope this helps.
The solution can be inferred in the third line of the error message:
Instead of performing asynchronous work inside a call to setState(), first execute the work (without updating the widget state), and then synchronously update the state inside a call to setState().)
So this means you'll have to perform the operation before refreshing the widget. You can have a temporary variable to hold the result of the asynchronous work and use that in your setState method:
onChanged: (text) {
setState(() => _futureData = _loadPhobias())
},
Could be written as:
onChanged: (text) async {
var phobias = _loadPhobias();
setState(() {
_futureData = phobias;
});
},

how to access flutter bloc in the initState method?

In the code shown below , the dispatch event is called from within the build method after getting the BuildContext object. What if I wish to do is to dispatch an event during processing at the start of the page within the initState method itself ?
If I use didChangeDependencies method , then I am getting this error :
BlocProvider.of() called with a context that does not contain a Bloc of type FileManagerBloc. how to fix this?
#override
Widget build(BuildContext context) {
return Scaffold(
body: BlocProvider<FileManagerBloc>(
builder: (context)=>FileManagerBloc(),
child: SafeArea(
child: Container(
child: Column(
children: <Widget>[
Container(color: Colors.blueGrey, child: TopMenuBar()),
Expanded(
child: BlocBuilder<FileManagerBloc,FileManagerState>(
builder: (context , state){
return GridView.count(
scrollDirection: Axis.vertical,
physics: ScrollPhysics(),
crossAxisCount: 3,
crossAxisSpacing: 10,
children: getFilesListWidget(context , state),
);
},
),
)
],
),
),
),
));
}
#override
void dispose() {
super.dispose();
}
#override
void didChangeDependencies() {
logger.i('Did change dependency Called');
final FileManagerBloc bloc = BlocProvider.of<FileManagerBloc>(context) ;
Messenger.sendGetHomeDir()
.then((path) async {
final files = await Messenger.sendListDir(path);
bloc.dispatch(SetCurrentWorkingDir(path)) ;
bloc.dispatch(UpdateFileSystemCacheMapping(path , files)) ;
});
}
The problem is that you are initializing the instance of FileManagerBloc inside the BlocProvider which is, of course inaccessible to the parent widget. I know that helps with automatic cleanup of the Bloc but if you want to access it inside initState or didChangeDependencies then you have to initialize it at the parent level like so,
FileManagerBloc _fileManagerBloc;
#override
void initState() {
super.initState();
_fileManagerBloc= FileManagerBloc();
_fileManagerBloc.dispatch(LoadEducation());
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: BlocProvider<FileManagerBloc>(
builder: (context)=> _fileManagerBloc,
child: SafeArea(
child: Container(
child: Column(
children: <Widget>[
Container(color: Colors.blueGrey, child: TopMenuBar()),
Expanded(
child: BlocBuilder<FileManagerBloc,FileManagerState>(
builder: (context , state){
return GridView.count(
scrollDirection: Axis.vertical,
physics: ScrollPhysics(),
crossAxisCount: 3,
crossAxisSpacing: 10,
children: getFilesListWidget(context , state),
);
},
),
)
],
),
),
),
));
}
#override
void dispose() {
_fileManagerBloc.dispose();
super.dispose();
}
#override
void didChangeDependencies() {
logger.i('Did change dependency Called');
Messenger.sendGetHomeDir()
.then((path) async {
final files = await Messenger.sendListDir(path);
_fileManagerBloc.dispatch(SetCurrentWorkingDir(path)) ;
_fileManagerBloc.dispatch(UpdateFileSystemCacheMapping(path , files)) ;
});
}
alternatively, if FileManagerBloc was provided/initialized at a grandparent Widget then it could easily be accessible at this level through BlocProvider.of<CounterBloc>(context);
you can use it in didChangeDependencies method rather than initState.
Example
#override
void didChangeDependencies() {
final CounterBloc counterBloc = BlocProvider.of<CounterBloc>(context);
//do whatever you want with the bloc here.
super.didChangeDependencies();
}
Solution:
Step 1: need apply singleton pattern on Bloc class
class AuthBloc extends Bloc<AuthEvent, AuthState> {
static AuthBloc? _instance;
static AuthBloc get instance {
if (_instance == null) _instance = AuthBloc();
return _instance!;
}
....
....
Step 2: use AuthBloc.instance on main.dart for Provider
void main() async {
runApp(MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => AuthBloc.instance,
),
...
...
],
child: App(),
));
}
Now you can use Bloc without context
you can get state by AuthBloc.instance.state from initState or anywhere
you can add event from anywhere by AuthBloc.instance.add(..)
you also call BlocA from another BlocB very simple

Flutter Provider doesn't rebuild widget

here's a piece of my code,
but please read the question before jumping to conclusions:
class RescheduleCard extends StatelessWidget {
#override
Widget build(BuildContext context)=> Consumer<AppSnapshot>(
builder: (context, appSnapshot, _)=>
(appSnapshot.reschedule!=null)
?RescheduleBuilder(
model: appSnapshot.reschedule,
controllers: appSnapshot.controllers,
)
:Carouselcard(
title: carouselPageTitle(title: rescheduleTitle,test: appSnapshot.test),
colors: yellows,
so I'm sort of new to provider and I'm used to Bloc,
my api once receive some call the provider and set a model;
edit: here's the provider 256 lines tripped down to what concern
the "reschedule"...
class AppSnapshot with ChangeNotifier {
RescheduleModel _reschedule;
RescheduleModel get reschedule => _reschedule;
void cleanReschedule() {
reschedule=null;
notifyListeners();
}
set reschedule(RescheduleModel reschedule) {
_reschedule=reschedule;
notifyListeners();
}
}
re-edit: on top of everything:
void main() async {
final AppSnapshot _appSnapshot = AppSnapshot();
await _appSnapshot.load();
runApp(ChangeNotifierProvider(
builder: (context) => _appSnapshot,
child: Initializer()));
}
I'm expecting the "Consumer" to rebuild my widget,
but doesn't!
I'm sure the data is there, because the widget is inside a carousel
and as soon as I move it it rebuilds properly.
what am I missing?
thank you
re-re-edit: here's an example of another Carousel Card where provider works quilckly and changes apply in realtime
Consumer<AppSnapshot>(
builder: (context, appSnapshot, _)=> Carouselcard(
title: carouselPageTitle(title: optionsTitle,test: appSnapshot.test),
colors: lightBlues,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
((appSnapshot.id??'')!='') // ID WIDGET
? ListTile(
leading: CustomIcon(
icon: deleteIcon,
onTap: () => appSnapshot.deleteID(),
),
title: _customCard(onTap:()=> _showID(id: appSnapshot.id,context: context)),
subtitle: Text(tap2delete,textScaleFactor:0.8),
)
: IdTile(),
According to this article the FutureProvider does not listen for changes, it will only rebuild Consumers 1 time, when Future is complete.
The article even explains how the author tested this.
The developer of the Dart Provider package also explains the use case for FutureProvider.
Specificies the type in main.dart
void main() async {
final AppSnapshot _appSnapshot = AppSnapshot();
await _appSnapshot.load();
runApp(ChangeNotifierProvider< **AppSnapshot** >(
builder: (context) => _appSnapshot,
child: Initializer()));
}