Update Cart badge counter in AppBar from multiple widgets - flutter

I am using a Reusable AppBar Widget which has title and action buttons.
In app bar actions, there is favorites icon button and cart icon button with a badge showing the total items in cart :
App Bar widget:
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
final BuildContext context;
final String title;
final bool showBackButton;
final Widget widget;
final bool showActions;
CustomAppBar({
#required this.context,
#required this.title,
this.showBackButton = true,
this.widget,
this.showActions = true,
});
#override
Widget build(BuildContext context) {
return AppBar(
title: Text(title),
leading: showBackButton
? new IconButton(
icon: new Icon(
Icons.arrow_back,
),
onPressed: () {
if (widget != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => widget,
),
);
return true;
} else {
Navigator.pop(context);
}
},
)
: null,
actions: !showActions ? null : <Widget>[
IconButton(
icon: const Icon(Icons.favorite_border),
onPressed: () {
Navigator.pushReplacement(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) {
return MainHome(
selectedIndex: 1,
);
},
),
);
},
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 5),
child: Badge(
position: BadgePosition.topEnd(top: 3, end: 3),
animationDuration: Duration(milliseconds: 300),
animationType: BadgeAnimationType.slide,
badgeColor: Colors.white,
toAnimate: true,
badgeContent: Text(
'5',
style: TextStyle(
fontSize: 8,
color: Theme.of(context).primaryColor,
fontWeight: FontWeight.bold),
),
child: IconButton(
icon: const Icon(Icons.shopping_cart_rounded),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) {
return MainHome(
selectedIndex: 2,
);
},
),
);
},
),
),
),
],
);
}
#override
Size get preferredSize {
return new Size.fromHeight(kToolbarHeight);
}
}
The app bar is used in all screens but with different parameters.
I want to update the counter in app bar whenever user add to cart, update cart, remove from cart. This can happens from multiple pages:
Products list page, product details page, shopping cart page, search suggestions widget. All of these pages have cart actions(add/update/delete).
I don't want to manage this counter in each page. I need a way to manage it in one place and be notified whenever cart updated in order to update badge
I searched a lot. Some uses GLobalKey to manage state but doesn't work in my case as the appbar widget is stateless cannot be stateful.

i suggest that you use any kind of providers like the provider package or riverpod , you need something called notifyListeners , to notify the cart badge every time you add a new item to your cart , otherwise you cart item in your case won't be updated except on widget rebuild ; like navigating and such .
you can check riverpod and provider from pub.dev , make sure to fully understand the docs because it can be tricky !
Hope this answer helps you !

what you want to do is to manage the state of the app. The way you are doing is pretty hard.
Maybe you should look at some state managment solution .
here is a link for a good intro and it talk about what you trying to acheive
intro to state managment
Here is a list of some popular state managment:
Provider (easy to use and recommanded by the Flutter Community)
Bloc (good for very large projects)
GetX (Easy and good to use)
Riverpod (It's provider but more powerful)
There is no a perfect of choice just use what you found good for need.

As suggested by Fahmi Sawalha and Boris Kamtou, I used the provider package to solve the problem.
I will share the code in case anyone needs it. The code helps you create custom AppBar as stateless widget with parameters like title, context, showBackButton, showActions.
And also the code helps you use the provider package to manage state and update ui from different screens.
First Create CartCounterNotifier class at any accessible place in your app. It should extend ChangeNotifier in order to notify listeners when value changed so that ui consuming this provider rebuilds:
CartManager is a Mixin where I manage cart data in DB.
getCartItemsCount() function gets the summation of items' quantities in cart.
cart_counter.dart
import 'package:flutter/material.dart';
class CartCounterNotifier extends ChangeNotifier with CartManager {
int _value = 0;
int get value => _value;
CartCounterNotifier() {
getCartItemsCount().then((counter) {
_value = counter ?? 0;
notifyListeners();
});
}
// You can send send parameters to update method. No need in my case.
// Example: void update(int newvalue) async { ...
void update() async {
int counter = await getCartItemsCount();
_value = counter ?? 0;
notifyListeners();
}
}
The class has two methods:
Constructor to initialize the counter and update() method to be called when value changed.
I have created custom appbar to use across all pages. It is a stateless widget which implements PreferedSizeWidget.
Wrap the widget where you want to show the counter with Consumer. It is better to go deep as possible. In my case, instead of wrapping the whole AppBar with consumer, I just wrapped the text widget showing the counter
custom_app_bar.dart
import 'package:badges/badges.dart'; // add badges to pubspec in order to add badge for icons
import 'package:flutter/material.dart';
import 'package:order_flutter_package/services/cart_counter.dart';
import 'package:order_flutter_package/ui/views/home_view/home_view.dart';
import 'package:provider/provider.dart';
class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
final BuildContext context;
final String title;
final bool showBackButton;
final Widget widget;
final bool showActions;
CustomAppBar({
#required this.context,
#required this.title,
this.showBackButton = true,
this.widget,
this.showActions = true,
});
#override
Widget build(BuildContext context) {
return PreferredSize(
preferredSize: Size.fromHeight(50),
child: AppBar(
title: Text(title),
leading: showBackButton
? new IconButton(
icon: new Icon(
Icons.arrow_back,
),
onPressed: () {
if (widget != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => widget,
),
);
return true;
} else {
Navigator.pop(context);
}
},
)
: null,
actions: !showActions
? null
: <Widget>[
IconButton(
icon: const Icon(Icons.favorite_border),
onPressed: () {
Navigator.pushReplacement(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) {
return MainHome(
selectedIndex: 1,
);
},
),
);
},
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 5),
child: Badge(
position: BadgePosition.topEnd(top: 3, end: 3),
animationDuration: Duration(milliseconds: 300),
animationType: BadgeAnimationType.slide,
badgeColor: Colors.white,
toAnimate: true,
badgeContent: Consumer<CartCounterNotifier>(
builder: (context, cartCounter, child) {
return Text(
cartCounter.value.toString(),
style: TextStyle(
fontSize: 8,
color: Theme.of(context).primaryColor,
fontWeight: FontWeight.bold),
);
}),
child: IconButton(
icon: const Icon(Icons.shopping_cart_rounded),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) {
return MainHome(
selectedIndex: 2,
);
},
),
);
},
),
),
),
],
),
);
}
#override
Size get preferredSize {
return new Size.fromHeight(kToolbarHeight);
}
}
Then wrap your main.dart app with ChangeNotifierProvider
import 'package:provider/provider.dart';
import 'package:order_flutter_package/services/cart_counter.dart';
ChangeNotifierProvider(
create: (context) => CartCounterNotifier(),
child: MyApp(),
)
Finally, in order to update counter, in any screen,
// Very important to import provider else you got an error
import 'package:provider/provider.dart';
// On button pressed or any event
var cartCounter = context.read<CartCounterNotifier>();
cartCounter.update();

Related

Update child from parent in Flutter

Currently, I have two sample files Parent.dart and Child.dart.
In Parent.dart file this is what the code is like:
Parent.dart file:
children:
[
isDisabled
? Icon(Icons.public, color: Colors.grey)
: Icon(Icons.public, color:Colors.white),
InkWell(
onTap:()=> Navigator.push(context,MaterialPageRoute(builder: (context)=> Child(
isDisabled: isDisabled, function: ()=> function())),
]
function()
{
setState(()=> isDisabled = !isDisabled);
}
and in Child.dart the code is something like this:
children:
[
widget.isDisabled
? Icon(Icons.public, color: Colors.grey)
: Icon(Icons.public, color:Colors.white),
InkWell(
onTap:()=> widget.function(),
]
I have some data being fetched from a server that is used to populate a list of cards inside listview.builder.
What I'm trying to do is inherent variables from the parent and use their value to update the child. Currently, if I run this parent does change, but the child doesn't until you navigate back from parent to child.
For a better context: Imagine a list of cards. Each has an add-to-list button. Now if you click on the card it goes to another screen "child.dart" where it gives you more details about the item on the card you clicked. Now if you click the add-to-list button on the child screen it should also update the parent.
I tried different ways of achieving this "UI synchrony" for a better user experience. But I didn't find a proper way to implement it.
Things I tried: Provider (but it updates all the items on the list instead of each instance.),
a "hacky" method of editing the data in the list on the client side and updating the widget based on that. (This technique does work, but ewwwww)
I'm not really sure to understand your question.
If your question is how trigger a function in parent from child screen, here is your answer.
I made a working example. I think you were really close.
Another option for state management is riverpod 2.0
Or you can pass value in Navigator.pop and trigger the function in parent.
Parent model
class Parent {
String title;
bool isDisabled = false;
Parent({required this.title});
}
Main.dart
import 'package:flutter/material.dart';
import 'parent.dart';
import 'ParentCard.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
MyApp({super.key});
List<Parent> parentList = [Parent(title: 'Item 1'), Parent(title: 'Item 2')];
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: ListView.builder(
itemCount: parentList.length,
itemBuilder: (BuildContext context, int position) {
return ParentCard(title: parentList[position].title);
},
),
),
);
}
}
ParentCard.dart
import 'package:flutter/material.dart';
import 'child.dart';
class ParentCard extends StatefulWidget {
String title;
ParentCard({super.key, required this.title});
#override
State<ParentCard> createState() => _ParentCardState();
}
class _ParentCardState extends State<ParentCard> {
bool isDisabled = false;
#override
Widget build(BuildContext context) {
return Row(
children: [
Text(widget.title),
isDisabled
? Icon(Icons.public, color: Colors.green)
: Icon(Icons.public, color: Colors.black),
IconButton(
icon: Icon(Icons.plus_one),
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ChildCard(isDisabled: isDisabled, handler: handler)),
),
)
],
);
}
handler() {
setState(() => isDisabled = !isDisabled);
}
}
** child.dart**
import 'package:flutter/material.dart';
class ChildCard extends StatefulWidget {
VoidCallback handler;
bool isDisabled;
ChildCard({super.key, required this.isDisabled, required this.handler});
#override
State<ChildCard> createState() => _ChildCardState();
}
class _ChildCardState extends State<ChildCard> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
const Text('child !'),
widget.isDisabled
? const Icon(Icons.public, color: Colors.green)
: const Icon(Icons.public, color: Colors.black),
ElevatedButton(
onPressed: () {
setState(() {
widget.isDisabled = !widget.isDisabled;
});
widget.handler();
},
child: const Text('click to trigger'),
),
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('pop it'),
)
]),
);
}
}

Main app widget: setState call -> build() builds all widgets but screen not updated

App is a simple memory/guessing game with a grid of squares. Floating action button triggers a "New game" dialog, and a Yes response triggers setState() on the main widget. The print() calls show it is building all the Tile widgets in the grid, but as it returns, the old grid values are still showing. Probably done something stupid but not seeing it. Basic code is below. TIA if anyone can see what is missing/invalid/broken/etc.
Main.dart is the usual main() that creates a stateless HomePage which creates a stateful widget which uses this State:
class MemHomePageState extends State<MemHomePage> {
GameBoard gameBoard = GameBoard();
GameController? gameController;
int gameCount = 0, winCount = 0;
#override
void initState() {
super.initState();
gameController = GameController(gameBoard, this);
}
#override
Widget build(BuildContext context) {
if (kDebugMode) {
print("MemHomepageState::build");
}
gameBoard.newGame(); // Resets secrets and grids
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: GridView.count(
crossAxisCount: Globals.num_columns,
children: List.generate(Globals.num_columns * Globals.num_rows, (index) {
int x = index~/Globals.NR, y = index%Globals.NR;
int secret = gameBoard.secretsGrid![x][y];
var t = Tile(x, y, Text('$secret'), gameController!);
gameBoard.tilesGrid![x].add(t);
if (kDebugMode) {
print("Row $x is ${gameBoard.secretsGrid![x]} ${gameBoard.tilesGrid![x][y].secret}");
}
return t;
}),
),
// Text("You have played $gameCount games and won $winCount."),
),
floatingActionButton: FloatingActionButton(
onPressed: () => newGameDialog("Start a new game?"),
tooltip: 'New game?',
child: const Icon(Icons.refresh_outlined),
),
);
}
/** Called from the FAB and also from GameController "won" logic */
void newGameDialog(String message) {
showDialog<void>(
context: context,
barrierDismissible: false, // means the user must tap a button to exit the Alert Dialog
builder: (BuildContext context) {
return AlertDialog(
title: Text("New game?"),
content: Text(message),
//),
actions: <Widget>[
TextButton(
child: const Text('Yes'),
onPressed: () {
setState(() {
gameCount++;
});
Navigator.of(context).pop();
},
),
TextButton(
child: const Text('No'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
}
);
}
The Tile class is a StatefulWidget whose state determines what that particular tile should show:
import 'package:flutter/material.dart';
import 'gamecontroller.dart';
enum TileMode {
SHOWN,
HIDDEN,
CLEARED,
}
/// Represents one Tile in the game
class Tile extends StatefulWidget {
final int x, y;
final Widget secret;
final GameController gameController;
TileState? tileState;
Tile(this.x, this.y, this.secret, this.gameController, {super.key});
#override
State<Tile> createState() => TileState(x, y, secret);
setCleared() {
tileState!.setCleared();
}
}
class TileState extends State<Tile> {
final int x, y;
final Widget secret;
TileMode tileMode = TileMode.HIDDEN;
TileState(this.x, this.y, this.secret);
_unHide() {
setState(() => tileMode = TileMode.SHOWN);
widget.gameController.clicked(widget);
}
reHide() {
print("rehiding");
setState(() => tileMode = TileMode.HIDDEN);
}
setCleared() {
print("Clearing");
setState(() => tileMode = TileMode.CLEARED);
}
_doNothing() {
//
}
#override
Widget build(BuildContext context) {
switch(tileMode) {
case TileMode.HIDDEN:
return ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.teal,
),
onPressed: _unHide,
child: Text(''));
case TileMode.SHOWN:
return ElevatedButton(
onPressed: _doNothing,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
),
child: secret);
case TileMode.CLEARED:
return ElevatedButton(
onPressed: _doNothing,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.black12,
),
child: const Icon(Icons.check));
}
}
}
it looks like you are calling the following in your build function. That would cause everything to reset everytime it builds. Perhaps it belongs in init instead?
gameBoard.newGame(); // Resets secrets and grids
The original problem is that the Tile objects, although correctly created and connected to the returned main widget, did not have distinct 'key' values so they were not replacing the originals. Adding 'key' to the Tile constructor and 'key: UniqueKey()' to each Tile() in the loop, solved this problem. It exposed a related problem but is out of scope for this question. See the github link in the OP for the latest version.

Flutter: Android: How to call setState() from another file?

For applying app's setting configuration to take effect around app i need to trigger main's setState from appSettings file, how to do so?
Files code:
for main.dart
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(isVibrationEnabled
? "Vibration is enabled"
: "Vibration is disabled"),
MaterialButton(
color: Colors.grey,
child: Text("Open app setting"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AppSettings(),
),
);
},
)
],
),
),
),
),
);
for globalVariables.dart
bool isVibrationEnabled = false;
for appSettings.dart
class _AppSettingsState extends State<AppSettings> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: FlatButton(
color: Colors.grey,
child: Text(
isVibrationEnabled ? "Disable Vibration" : "Enable Vibration"),
onPressed: () {
setState(() {
isVibrationEnabled
? isVibrationEnabled = false
: isVibrationEnabled = true;
});
//What to do here to trigger setState() in main.dart flie
//for displaying "Vibration is enabled" or "Vibration is disabled"
//acording to the value of bool variable which is in globalVariable.dart file.
},
),
),
),
);
i have seen other answer on stackoverflow but none of them are easy to understand, if someone can answer in a easy way please
For your specific use case, I think best is to use a state management solution like Provider, BLoC, or GetX. Docs here:
https://flutter.dev/docs/development/data-and-backend/state-mgmt/options
If you want something quick and easy, you can pass the value you're listening to and a function containing setState to your new page. Normally you'd do this with a child widget rather than new page, so it might get a bit complicated -- you'll need to rebuild the entire page after the setState. Easiest way I can think of doing that is with Navigator.pushReplacement.
Some code (I wrote this in stackoverflow not my IDE so probably has errors):
class AppSettings extends StatefulWidget {
final Function callback;
final bool isVibrationEnabled;
AppSettings({
#required this.callback,
#required this.isVibrationEnabled,
});
}
...
In your AppSettingsState use:
FlatButton(
color: Colors.grey,
child: Text(
widget.isVibrationEnabled ? "Disable Vibration" : "Enable Vibration"),
onPressed: () => widget.callback(),
),
And in your main file, when creating your appsettings use something like:
MaterialButton(
color: Colors.grey,
child: Text("Open app setting"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AppSettings(
isVibrationEnabled: isVibrationEnabled,
callback: callback,
),
),
);
},
)
void Function callback() {
setState(() => isVibrationEnabled = !isVibrationEnabled);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => AppSettings(
isVibrationEnabled: isVibrationEnabled,
callback: callback,
),
),
);
}
Again, you should probably use a state management solution for this specific use case. Rebuilding a page from another page seems messy. But it should work.
And yes, you're using the callback within your callback. So you may need to put the callback near the top of your file, or outside the main function to make it work right.

MyStateObject was disposed when I navigated back from Screen2 to Screen1

I will post my projects minimum classes here that you can reproduce the faulty behavior.
The listing of the classes here goes mostly from the top of the flutter widget hierarchy down the rest...
main.dart
import 'package:TestIt/widgets/applicationpage.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
final ApplicationPage applicationPage =
ApplicationPage(title: 'Flutter Demo');
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
primarySwatch: Colors.blue,
),
home: applicationPage);
}
}
applicationpage.dart
import 'package:flutter/material.dart';
import 'body.dart';
class ApplicationPage extends StatefulWidget {
ApplicationPage({Key key, this.title}) : super(key: key);
final String title;
#override
_ApplicationPageState createState() => _ApplicationPageState();
}
class _ApplicationPageState extends State<ApplicationPage> {
final Body body = new Body();
#override
Widget build(BuildContext context) {
return Scaffold(
body: body);
}
}
body.dart
import 'package:TestIt/viewmodels/excercise.dart';
import 'package:TestIt/viewmodels/workout.dart';
import 'package:flutter/material.dart';
import 'Excercises/ExcerciseListWidget.dart';
class Body extends StatelessWidget {
#override
Widget build(BuildContext context) {
var workouts = new List<Workout>();
var pullDay = new Workout("Pull day", new List<Excercise>());
workouts.add(pullDay);
return Container(
margin: EdgeInsets.all(5),
child: DefaultTabController(
// Added
length: workouts.length, // Added
initialIndex: 0, //Added
child: Scaffold(
appBar: PreferredSize(
// todo: add AppBar widget here again
preferredSize: Size.fromHeight(50.0),
child: Row(children: <Widget>[
TabBar(
indicatorColor: Colors.blueAccent,
isScrollable: true,
tabs: getTabs(workouts),
),
Container(
margin: EdgeInsets.only(left: 5.0),
height: 30,
width: 30,
child: FloatingActionButton(
heroTag: null,
child: Icon(Icons.add),
backgroundColor: Colors.red,
foregroundColor: Colors.white,
elevation: 5.0,
onPressed: () => print("add workout"))),
Container(
margin: EdgeInsets.only(left: 5.0),
height: 30,
width: 30,
child: FloatingActionButton(
heroTag: null,
child: Icon(Icons.remove),
backgroundColor: Colors.red,
foregroundColor: Colors.white,
elevation: 5.0,
onPressed: () => print("add workout"))),
])),
body: TabBarView(
children: getTabViews(workouts),
),
)));
}
List<ExcerciseListWidget> getTabViews(List<Workout> workouts) {
var tabViews = new List<ExcerciseListWidget>();
for (var i = 0; i < workouts.length; i++) {
tabViews.add(ExcerciseListWidget(workouts[i].excercises));
}
return tabViews;
}
List<Tab> getTabs(List<Workout> workouts) {
Color textColor = Colors.blueAccent;
return workouts
.map((w) => new Tab(
child: Text(w.name, style: TextStyle(color: textColor)),
))
.toList();
}
}
ExcerciseListWidget.dart
import 'package:TestIt/viewmodels/excercise.dart';
import 'package:flutter/material.dart';
import 'ExcerciseWidget.dart';
class ExcerciseListWidget extends StatefulWidget {
ExcerciseListWidget(this.excercises);
final List<Excercise> excercises;
#override
_ExcerciseListWidgetState createState() => _ExcerciseListWidgetState();
}
class _ExcerciseListWidgetState extends State<ExcerciseListWidget> {
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
widget.excercises.insert(
0,
new Excercise(widget.excercises.length + 1, "test",
widget.excercises.length * 10));
});
},
child: Icon(Icons.add),
backgroundColor: Colors.red,
foregroundColor: Colors.white,
elevation: 5.0,
),
body: Container(
padding: const EdgeInsets.all(2),
child: ReorderableListView(
onReorder: (index1, index2) => {
print("onReorder"),
},
children: widget.excercises
.map((excercise) => ExcerciseWidget(
key: ValueKey(excercise.id), excercise: excercise))
.toList())));
}
}
ExcerciseWidget.dart
import 'package:TestIt/viewmodels/excercise.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'ExcerciseDetailsWidget.dart';
class ExcerciseWidget extends StatefulWidget {
ExcerciseWidget({this.key, this.excercise}) : super(key: key);
final Excercise excercise;
final Key key;
#override
_ExcerciseWidgetState createState() => _ExcerciseWidgetState();
}
class _ExcerciseWidgetState extends State<ExcerciseWidget> {
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 3.0, bottom: 3.0),
// TODo: with this ink box decoration the scrolling of the excercises goes under the tabbar... but with the ink I have a ripple effect NOT under
// the element...
child: Ink(
decoration: BoxDecoration(
borderRadius: new BorderRadius.all(new Radius.circular(5.0)),
border: Border.all(color: Colors.orange),
color: Colors.green),
child: InkWell(
onTap: () => {navigateToEditScreen(context)},
child: Column(
children: <Widget>[
Container(
color: Colors.red, child: Text(widget.excercise.name)),
],
)),
));
}
navigateToEditScreen(BuildContext context) async {
final Excercise result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ExcerciseDetailsWidget(excercise: widget.excercise)));
setState(() {
widget.excercise.name = result.name;
});
}
}
ExcerciseDetailsWidget.dart
import 'package:TestIt/viewmodels/excercise.dart';
import 'package:flutter/material.dart';
class ExcerciseDetailsWidget extends StatefulWidget {
final Excercise excercise;
ExcerciseDetailsWidget({Key key, #required this.excercise}) : super(key: key);
#override
_ExcerciseDetailsWidgetState createState() => _ExcerciseDetailsWidgetState();
}
class _ExcerciseDetailsWidgetState extends State<ExcerciseDetailsWidget> {
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.excercise.name),
),
body: Padding(
padding: EdgeInsets.only(left: 20, right: 20, bottom: 2, top: 2),
child: Form(
key: _formKey,
child: Column(children: <Widget>[
new RaisedButton(
elevation: 2,
color: Colors.blue,
child: Text('Save'),
onPressed: () {
setState(() {
widget.excercise.name = "new name";
});
Navigator.pop(context, widget.excercise);
}),
TextFormField(
decoration: InputDecoration(
//hintText: 'excercise name',
labelText: 'Excercise name',
),
initialValue: widget.excercise.name,
),
]))));
}
}
workout.dart
import 'excercise.dart';
class Workout{
Workout(this.name, this.excercises);
String name;
List<Excercise> excercises;
}
excercise.dart
class Excercise {
int id;
Excercise(this.id,this.name, this.restBetweenSetsInSeconds);
String name;
int restBetweenSetsInSeconds;
}
How to reproduce the faulty behavior to get the exception:
Click on the bottom-right floating action button to create an excercise test stub which is added to the only existing workout.
Click the newly added excercise
The ExcerciseDetailsWidget is loaded
Click Save in the ExcerciseDetailsWidget
Navigation goes back to the Initial screen and the Exception hits you in the face bam!
Exception
FlutterError (setState() called after dispose(): _ExcerciseWidgetState#bccdb(lifecycle state: defunct, not mounted)
This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().)
Question
Why is the formerly added and clicked ExcerciseWidget`s State disposed when I returned from the ExcerciseDetailsWidget ?
Check for is mounted and then call setState is no solution because in any case the excercise should NOT be disposed because I have to update it with the new excercise name.
If you know a flutter online site where I can put the project I will do so please let me know!
I am a flutter beginner maybe I do something completely wrong bear that in mind :-)
UPDATE
What I have done to workaround the problem is:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ExcerciseDetailsWidget(excercise: widget.excercise)));
do not await the result of the Navigator.
Instead I do this in the Screen2:
onPressed: () {
if (_formKey.currentState.validate()) {
// WHY can I set here the new text WITHOUT setState but when I navigated back the new excercise name is reflected in the list of excercises. Actually that should not be the case right? That confuses me totally.
widget.excercise.name =
excerciseNameTextController.value.text;
Navigator.pop(context);
}
},
but this is really just a workaround that works in this special EDIT use case.
When I have an ADD use case I need to return something to add it to the list of excercises...
Could it be that the problem is that I await the result inside the excercise?
I guess I will try to await the result excercise on the context/level of the ExercerciseListWidget not inside the ExcerciseWidget.
UPDATE 2
Reading more about the navigator it seems or could be that when I am navigating back to the former route which is my initial/root that all the knowledge about the clicked excercise is gone? Do I need therefore kind of nested routing? like "/workouts/id/excercises/id" ?
Despite the downvotes, this is a legitimate question. After poking around a little bit, the reason seems to be the ReorderableListView. For some reason, even if you are providing keys to each child of the list, when the ReorderableListView is rebuilt, all of its children are disposed and reinitialized. Because of this, when you navigate back from ExcerciseDetailsWidget, you are calling setState within a state that has been disposed - this is why you are getting that specific exception.
Frankly, your current code makes it very difficult to figure out whether it's something you've done wrong or a bug related to ReorderableListView. The only thing that can be said for sure is that replacing the ReorderableListView with a regular ListView will fix it.
I highly recommend cleaning up your code first - my IDE lit up like a Christmas tree when I copied your code in. Get rid of the new keyword. Use const constructors. Fix the Excercise typo that repeats itself 60 times in 250 rows of code.
And most importantly, given that you are mutating and displaying a data object across multiple stateful widgets, start using Provider for state management.

Passing data between Widgets without using Navigator?

I've some struggling with flutter.
I've two widget Details screen so in the first Details, I have a list and I want to send it to the second Screen without using navigator.
So if there is anyone who can help me I will be very thankful.
Details :
List<String> _instructions = [];
class Details extends StatefulWidget {
#override
_DetailsState createState() => new _DetailsState();
}
class _DetailsState extends State<Details> {
Expanded(
child: Container(
margin: EdgeInsets.all(3),
child: OutlineButton(
highlightElevation: 21,
color: Colors.white,
shape: StadiumBorder(),
textColor: Colors.lightBlue,
child: Text(
'ENVOYER',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.normal,
color: Colors.lightBlue,
),
),
borderSide: BorderSide(
color: Colors.lightBlue,
style: BorderStyle.solid,
width: 1),
onPressed: () {
},
),
),
),
}}
so what I want is that,when I press the button I will send my list to the next widget without using navigator.
you can use the sharedpreferance which is the simple xml that belongs to the application. And this is how you can set it
Future<bool> setStringList(String key, List<String> value) =>
_setValue('StringList', key, value);
Future<bool> setStringList (
String key,
List<String> value
)
For more info here is a link
And you can get your List by
List<String> getStringList(String key) {
List<Object> list = _preferenceCache[key];
if (list != null && list is! List<String>) {
list = list.cast<String>().toList();
_preferenceCache[key] = list;
}
return list;
}
Also you can use sqflite
Suppose you have two pages, namely 'page1.dart' and 'page2.dart', both want to access the same list:
Create another dart file 'GlobalVariables.dart', inside this file, create a class gv.
Inside this class gv, create a static list by using:
static List <String> listAnyList = [];
import 'GlobalVariables.dart' in the 2 pages that need to access this list.
Now, in page1.dart and page2.dart,
you can use gv.listAnyList to access the 'Global List'.
Use 'Global Static Variables' if a variable is needed in many dart files, e.g. the 'User ID', then you can simply use gv.strUserID to access it in any pages you want.
I think a more appropriate approach should be similar to how android fragments connect to each other using bloc pattern or master-details flow.
I created an example repository to show the complete concept.
In short, the idea is to create a class with StreamController inside. Both widgets will have a reference to bloc instance. When the first widget wants to send data to the second it adds a new item to Stream. The second listen to the stream and updates its content accordingly.
Inside bloc:
StreamController<String> _selectedItemController = new BehaviorSubject();
Stream<String> get selectedItem => _selectedItemController.stream;
void setSelected(String item) {
_selectedItemController.add(item);
}
First fragment:
class FragmentList extends StatelessWidget {
final Bloc bloc;
const FragmentList(
this.bloc, {
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: bloc.selectedItem,
initialData: "",
builder: (BuildContext context, AsyncSnapshot<String> screenType) {
return ListView.builder(
itemBuilder: (context, index) {
return ListTile(
selected: bloc.items[index] == screenType.data,
title: Text(bloc.items[index]),
onTap: () {
bloc.setSelected(bloc.items[index]);
},
);
},
itemCount: bloc.items.length,
);
},
);
}
}
The second fragment:
class FragmentDetails extends StatelessWidget {
final Bloc bloc;
const FragmentDetails(
this.bloc, {
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Center(
child: StreamBuilder(
initialData: "Nothing selected",
stream: bloc.selectedItem,
builder: (BuildContext context, AsyncSnapshot<String> screenType) {
final info = screenType.data;
return Text(info);
},
),
);
}
}