Flutter setstate method doesn't add my numbers - flutter

I built custom app for training. I created buttons with gesture detector and i assigned number to them and i created global variable "score". I want buttons to add their numbers to "score" variable and i want to show the variable in a container but Somehow it does not work.Can it be about states?Does anyone help me?
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.deepPurple,
centerTitle: true,
elevation: 3,
),
),
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("My Application"),
),
body: const Body(),
);
}
}
int score = 5;
class Body extends StatefulWidget {
const Body({Key? key}) : super(key: key);
#override
State<Body> createState() => _BodyState();
}
class _BodyState extends State<Body> {
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: 50,
width: 200,
decoration: const BoxDecoration(color: Colors.grey),
child: Center(child: Text(score.toString())),
),
const SizedBox(
height: 70,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Numb(
color: Colors.pink,
numb: 1,
),
Numb(
color: Colors.pink,
numb: 2,
),
Numb(
color: Colors.pink,
numb: 3,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Numb(
color: Colors.pink,
numb: 4,
),
Numb(
color: Colors.pink,
numb: 5,
),
Numb(
color: Colors.pink,
numb: 6,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Numb(
color: Colors.pink,
numb: 7,
),
Numb(
color: Colors.pink,
numb: 8,
),
Numb(
color: Colors.pink,
numb: 9,
),
],
),
],
);
}
}
class Numb extends StatefulWidget {
final int? numb;
final Color? color;
const Numb({
Key? key,
required this.numb,
required this.color,
}) : super(key: key);
#override
State<Numb> createState() => _NumbState();
}
class _NumbState extends State<Numb> {
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
score += widget.numb!;
});
},
child: Container(
margin: projectPadding.allPad * 0.5,
decoration: BoxDecoration(color: widget.color),
height: MediaQuery.of(context).size.height * 0.06,
width: MediaQuery.of(context).size.width * 0.1,
child: Center(
child: Text(widget.numb.toString()),
),
),
);
}
}
class projectPadding {
static const EdgeInsets horizantalPad = EdgeInsets.symmetric(horizontal: 20);
static const EdgeInsets verticalPad = EdgeInsets.symmetric(vertical: 20);
static const EdgeInsets allPad = EdgeInsets.all(20);
}

Numb setState only update the _NumbState ui. in order to update parent widget, you can use callback method that will trigger setState on parent UI.
class Numb extends StatefulWidget {
final int? numb;
final Color? color;
final Function(int) callBack;
const Numb({
Key? key,
required this.numb,
required this.color,
required this.callBack,
}) : super(key: key);
#override
State<Numb> createState() => _NumbState();
}
///....
onTap: () {
setState(() {
score += widget.numb!;
});
widget.callBack(score);
},
And you can add logic and others operation like
Numb(
color: Colors.pink,
numb: 1,
callBack: (p0) {
setState(() {});
},
),
I will also recommend starting state-management like riverpod / bloc

Why doesn't it work?
When you use the setState method, it triggers a rebuild of the widget where it is called.
In your code, you call the setState method in your Numb widget, which will therefore be rebuilt.
The problem is that the score value that you display on screen is located in your Body widget, and you want this widget to be rebuilt whenever the score changes.
So how do we do that?
How to make it work?
This is a State Management issue and there are multiple ways to solve it. You can find in the official documentation a good example to understand how this works.
Lifting the State Up and Callbacks
Following the previous logic described above, you would have to call the setState method in the Body widget to trigger a rebuild, and this whenever the score changes, which means whenever a Numb widget is pressed.
For that you can take advantage of callbacks which are basically functions that you can pass as parameters, and that will run the code they contain when they are called (you can see the official documentation's example about accessing a state using callbacks).
class Numb extends StatelessWidget { //<-- you can turn Numb into a StatelessWidget which is much simpler since you don't have to call the 'setState' method in it
final int? numb;
final Color? color;
final Function(int) callback; //<-- add your callback as a field...
const Numb({
Key? key,
required this.numb,
required this.color,
required this.callback, //<-- ... and in the constructor...
}) : super(key: key);
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => callback(numb!), //<-- ... and simply call it this way in the onTap parameter, giving it the numb value
child: Container(
margin: projectPadding.allPad * 0.5,
decoration: BoxDecoration(color: color),
height: MediaQuery.of(context).size.height * 0.06,
width: MediaQuery.of(context).size.width * 0.1,
child: Center(
child: Text(numb.toString()),
),
),
);
}
}
class _BodyState extends State<Body> {
#override
Widget build(BuildContext context) {
var updateScoreCallback = (int number) => setState(() => score += number); //<-- your callback takes an int as parameter and call setState adding the input number to the score
return Column(
children: [
...,
Numb(
color: Colors.pink,
numb: 1,
callback: updateScoreCallback, //<-- give your callback to your Numb widgets
),
Numb(
color: Colors.pink,
numb: 2,
callback: updateScoreCallback,
),
...
}
}
Like that, pressing any of your Numb widget will call the callback, that will call the setState method in the appropriate Body widget.
State Management with Packages
The previous method to handle state management with callbacks is good when your case is simple, but if you need for example to access a state from multiple places in your code, it can be quickly too difficult to manage and inefficient. For that, there are multiple packages that are available to make things easier. The official recommandation to start with is the Provider package as it is simple to use, but depending on your need you may want to look for other options like BLoC, Redux, GetX, etc. (full list of state management approaches.
Using the Provider approach, start by adding the package in your project (flutter pub add provider), and add the following changes to your code:
import 'package:provider/provider.dart';
class ScoreData with ChangeNotifier { //<-- create a structure to hold your data, and use the mixin 'ChangeNotifier' to make ScoreData able to notify its listeners for any changes
int _score = 5;
int get score => _score;
void addToScore(int number) {
_score += number;
notifyListeners(); //<-- this method comes from ChangeNotifier (which comes from the Flutter SDK and not from the Provider package), and notify all listeners
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("My Application"),
),
body: ChangeNotifierProvider<ScoreData>( //<-- this says that at this level of the widget tree, you provide a ScoreData that can notify its listeners for any changes...
create: (context) => ScoreData(), //<-- ... and you provide the ScoreData here by creating a new one (you can provide an existing one using the "value" parameter)
child: const Body(),
),
);
}
}
class Body extends StatefulWidget {
const Body({Key? key}) : super(key: key);
#override
State<Body> createState() => _BodyState();
}
class _BodyState extends State<Body> {
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: 50,
width: 200,
decoration: const BoxDecoration(color: Colors.grey),
child: Center(
child: Text(Provider.of<ScoreData>(context).score.toString())), //<-- this enables you to retrieve the provided ScoreData higher in the widget tree, and to listen to its value
),
...
],
);
}
}
class Numb extends StatelessWidget {
final int? numb;
final Color? color;
const Numb({
Key? key,
required this.numb,
required this.color,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () =>
Provider.of<ScoreData>(context, listen: false).addToScore(numb!), //<-- here as well you retrieve the provided ScoreData, but you only want to call its method "addToScore" without needing to listen to its changes, so add the "listen: false" parameter to make it work
child: Container(
...
),
);
}
}

Related

Flutter) I want to change screen in ModalBottomSheet... WHAT IS PROBLEM..?

I made an int variable tab1 and a function addTab to control the screen in modalBottomSheet, and I thought that when TextButton in HandAdd1() is pressed, a function addTab is executed, and changes the int variable tab1.
In MyApp(), as a result HandAdd2() widget is shown according to the list in MyApp(), but int variable tab1 doesn't change no matter how many times I press the TextButton in HandAdd1(), so the screen doesn't change, and I don't know what the problem is.
Can you help me ?
Here's the code:
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int tab1 = 0;
addTab (){
setState(() {
tab1++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton:FloatingActionButton.extended(
onPressed: () {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return Container(
padding:EdgeInsets.fromLTRB(20,30,20,20),
height:MediaQuery.of(context).size.height * 50,
margin: const EdgeInsets.only(
left: 0,
right: 0,
bottom: 0,
),
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft:Radius.circular(25),
topRight: Radius.circular(25),
),
),
child: Scaffold(body:[HandAdd1(addTab:addTab) , HandAdd2()][tab1]),
);
},
backgroundColor: Colors.transparent,
);
);
}
}
and here's HandAdd1() WIdget. (HandAdd2() is almost similar to HandAdd1())
class HandAdd1 extends StatefulWidget {
const HandAdd1({Key? key, this.addTab}) : super(key: key);
final void addTab;
#override
HandAdd1State createState() => HandAdd1State();
}
class HandAdd1State extends State<HandAdd1> {
#override
Widget build(BuildContext context) {
return Column(
children:[
Align(alignment:Alignment.centerLeft, child:Padding(
padding:EdgeInsets.fromLTRB(0,20,0,0,),
child:Text('''title''' ,
),
),
),
Padding(
padding:EdgeInsets.fromLTRB(0,20,0,20,),
child:Container(),
),
InkWell(child: Container(
margin:EdgeInsets.fromLTRB(0,20,0,0,),
alignment:Alignment.center,
width: MediaQuery.of(context).size.width * 50,
height:60,
decoration: BoxDecoration(
borderRadius:BorderRadius.all(Radius.circular(10)),
color: Colors.pinkAccent,
),
child:Text('button' , style: TextStyle(color:Colors.white , fontWeight:FontWeight.w500 , fontSize: 20,))
),
onTap: (){
widget.addTab;
}
),
],
);
}
}
You need to pass addTab function to a addTab property as a VoidCallback.
In your HandAdd1 widget,
Change from final void addTab; to final VoidCallback addTab;
And from widget.addTab; to widget.addTab();

Call a function inside Flutter Widget

I am pretty new to OOP and Flutter. I created the following widget and want to call the widget function when creating it inside another stateless Widget.
My plan is to create the widget as a child and then use the defined variable widgetState to check if it is true and if it is, it should call the void printSample() function. The conditional check shout be triggered by onTap of the widget (InkWell).
Widget with the Function:
class WhiteCard extends StatelessWidget {
final widgetState = true;
final VoidCallback onTap;
final Color switchColor = Colors.red;
void printSample() {
print("Sample text");
}
const WhiteCard({
Key? key,
required this.onTap,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return InkWell(
onTap: onTap,
child: Container(
width: 320,
height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18),
color: Colors.white,
),
child: Center(
child: ScreenController.isLargeScreen(context)
? Text("large")
: ScreenController.isMediumScreen(context)
? Text("medium")
: Text("small"),
),
),
);
}
}
Widget that calls the WhiteCard()
class LargeScreen extends StatelessWidget {
const LargeScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Expanded(
child: Container(
color: Colors.orangeAccent,
child: Center(
child: WhiteCard(
onTap: () {
CALL THE FUNCTION FROM WIDGET);
},
),
),
),
);
}
}
You can also define a function to leave the definition of object cleaner:
class LargeScreen extends StatelessWidget {
const LargeScreen({Key? key}) : super(key: key);
onTapFunction() {
// write he whatever you need to do when taping widget
}
#override
Widget build(BuildContext context) {
return Expanded(
child: Container(
color: Colors.orangeAccent,
child: Center(
child: WhiteCard(
onTap: onTapFunction,
),
),
),
);
}
}
So if you need to call the onTapFunction from elsewhere, you can.
Well if I understood your question correctly then your onTap should be something like this:
onTap: () {
if (widgetState) {
printSample();
}
Good luck, Feel free to respond if you have queries

where does FocusScope widget exist in the widget tree?

Where does the FocusScope widget create in the tree and we pass every context in it and it can request to any focus nodes. When we pass context to FocusScope it will start looking above the context and we never used the FocusScope widget in the code in the hierarchy where does it create and how does it resolves in the case of scaffold if we pass context that is above in the tree then it throws an exception then we use builder type of thing but in FocusScope why it doesn't throw an error?
Here is the example for the FocusScope
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
/// A demonstration pane.
///
/// This is just a separate widget to simplify the example.
class Pane extends StatelessWidget {
const Pane({
Key? key,
required this.focusNode,
this.onPressed,
required this.backgroundColor,
required this.icon,
this.child,
}) : super(key: key);
final FocusNode focusNode;
final VoidCallback? onPressed;
final Color backgroundColor;
final Widget icon;
final Widget? child;
#override
Widget build(BuildContext context) {
return Material(
color: backgroundColor,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Center(
child: child,
),
Align(
alignment: Alignment.topLeft,
child: IconButton(
autofocus: true,
focusNode: focusNode,
onPressed: onPressed,
icon: icon,
),
),
],
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool backdropIsVisible = false;
FocusNode backdropNode = FocusNode(debugLabel: 'Close Backdrop Button');
FocusNode foregroundNode = FocusNode(debugLabel: 'Option Button');
#override
void dispose() {
super.dispose();
backdropNode.dispose();
foregroundNode.dispose();
}
Widget _buildStack(BuildContext context, BoxConstraints constraints) {
final Size stackSize = constraints.biggest;
return Stack(
fit: StackFit.expand,
// The backdrop is behind the front widget in the Stack, but the widgets
// would still be active and traversable without the FocusScope.
children: <Widget>[
// TRY THIS: Try removing this FocusScope entirely to see how it affects
// the behavior. Without this FocusScope, the "ANOTHER BUTTON TO FOCUS"
// button, and the IconButton in the backdrop Pane would be focusable
// even when the backdrop wasn't visible.
FocusScope(
// TRY THIS: Try commenting out this line. Notice that the focus
// starts on the backdrop and is stuck there? It seems like the app is
// non-responsive, but it actually isn't. This line makes sure that
// this focus scope and its children can't be focused when they're not
// visible. It might help to make the background color of the
// foreground pane semi-transparent to see it clearly.
canRequestFocus: backdropIsVisible,
child: Pane(
icon: const Icon(Icons.close),
focusNode: backdropNode,
backgroundColor: Colors.lightBlue,
onPressed: () => setState(() => backdropIsVisible = false),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// This button would be not visible, but still focusable from
// the foreground pane without the FocusScope.
ElevatedButton(
onPressed: () => debugPrint('You pressed the other button!'),
child: const Text('ANOTHER BUTTON TO FOCUS'),
),
DefaultTextStyle(
style: Theme.of(context).textTheme.headline2!,
child: const Text('BACKDROP')),
],
),
),
),
AnimatedPositioned(
curve: Curves.easeInOut,
duration: const Duration(milliseconds: 300),
top: backdropIsVisible ? stackSize.height * 0.9 : 0.0,
width: stackSize.width,
height: stackSize.height,
onEnd: () {
if (backdropIsVisible) {
backdropNode.requestFocus();
} else {
foregroundNode.requestFocus();
}
},
child: Pane(
icon: const Icon(Icons.menu),
focusNode: foregroundNode,
// TRY THIS: Try changing this to Colors.green.withOpacity(0.8) to see for
// yourself that the hidden components do/don't get focus.
backgroundColor: Colors.green,
onPressed: backdropIsVisible
? null
: () => setState(() => backdropIsVisible = true),
child: DefaultTextStyle(
style: Theme.of(context).textTheme.headline2!,
child: const Text('FOREGROUND')),
),
),
],
);
}
#override
Widget build(BuildContext context) {
// Use a LayoutBuilder so that we can base the size of the stack on the size
// of its parent.
return LayoutBuilder(builder: _buildStack);
}
}

How to use a Checkbox to change text in Flutter/Dart using an array/list (troubles with onChanged/setState)

Thanks in advance, I am fairly new to this and have followed a few tutorials and read countless posts here.
I am working on a personal project and have struck a dead end.
I wish to change the text within a text widget by use of a checkbox, in essence turning it on and off.
Unfortunately what at first seemed simple has driven me insane for the last week or so, I apologize if this has been answered but I can't find the help I need, I have found things similar but nothing has worked so far.
I'm trying to change my int value with an onchanged and set staff function with a list/array and an int value, I effectively want to set the value from 0 to 1 and then back again.
var textChange = [" could be ", " have become "];
int t = 0;
with;
onChanged: (value) {
setState(() {
boxChecked = value!;
if (boxChecked) {
t = 1;
} else if (!boxChecked){
t = 0;
}
}
);
},
I have made sure I am extending a Stateful Widget tried setting up different functions and methods to pass through, I have tried using a material button instead of a checkbox but still hit the same issue.
I have tried a few different ways to write my onset function including something as simple as [t++ or t = (d + 1) % textChange.length;] but these would ultimately end in error once the int = >2, but I couldn't even get the value of my int to change.
If I changed it manually and run the program, it works. however, I can't seem to get my onchanged and set state code to affect my array or int.
I even had my original array as List, changed it to var in hopes it would make it mutable.
I hope I said that right, I am clearly missing something but I've looked at so much I'm just lost.
Below is the code I have used with the fat trimmed from the rest of my project. I'm using android studios with the latest updates.
Thanks for your help and time.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'alternate text code',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'alternate text'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Divider(),
Container(
width: MediaQuery.of(context).size.width / 1.2,
child:
Text(
'I am having trouble getting some code to work, I have tried '
'a lot of things but can't work it out.'
'I would like the check box to change the line of text below,
),
),
Divider(),
Container(
width: MediaQuery.of(context).size.width / 1.2,
child:
ChangeText(),
),
Divider(),
Container(
width: MediaQuery.of(context).size.width / 1.2,
child:
Text(
'you' + textChange[t] + 'a App Developer.',
),
),
],
),
),
);
}
}
bool boxChecked = false;
class ChangeText extends StatefulWidget {
const ChangeText({Key? key}) : super(key: key);
#override
State<ChangeText> createState() => _ChangeText();
}
var textChange = [" could be ", " have become "];
int t = 0;
class _ChangeText extends State<ChangeText> {
#override
Widget build(BuildContext context) {
return Expanded(
child:
Container(
child: CheckboxListTile(
title: const Text('learn Flutter', style: TextStyle(fontSize: 14),),
value: boxChecked,
onChanged: (value) {
setState(() {
boxChecked = value!;
if (boxChecked) {
t = 1;
} else if (!boxChecked){
t = 0;
}
}
);
},
),
),
);
}
}
From ChangeText widget, you are calling setState mean it will only change the UI within ChangeText widget. However, Text reflect need to happened on MyHomePage. You can use global key to change the parent state or just use callback method like
class ChangeText extends StatefulWidget {
final Function callBack;
const ChangeText({
Key? key,
required this.callBack,
}) : super(key: key);
........
onChanged: (value) {
setState(() {
boxChecked = value!;
if (boxChecked) {
t = 1;
} else if (!boxChecked) {
t = 0;
}
});
widget.callBack();
},
and use like
child: ChangeText(
callBack: () {
setState(() {});
},
),
Full Widgets
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'alternate text code',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'alternate text'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Divider(),
Container(
width: MediaQuery.of(context).size.width / 1.2,
child: Text(
'I am having trouble getting some code to work, i have tried '
'a lot of things but cant work it out.'
'I would like the check box to change the line of text below',
),
),
Divider(),
Container(
width: MediaQuery.of(context).size.width / 1.2,
child: ChangeText(
callBack: () {
setState(() {});
},
),
),
Divider(),
Container(
width: MediaQuery.of(context).size.width / 1.2,
child: Text(
'you' + textChange[t] + 'a App Developer.',
),
),
],
),
),
);
}
}
bool boxChecked = false;
class ChangeText extends StatefulWidget {
final Function callBack;
const ChangeText({
Key? key,
required this.callBack,
}) : super(key: key);
#override
State<ChangeText> createState() => _ChangeText();
}
var textChange = [" could be ", " have become "];
int t = 0;
class _ChangeText extends State<ChangeText> {
#override
Widget build(BuildContext context) {
return
// Expanded(
// child:
Container(
child: CheckboxListTile(
title: const Text(
'learn Flutter',
style: TextStyle(fontSize: 14),
),
value: boxChecked,
onChanged: (value) {
setState(() {
boxChecked = value!;
if (boxChecked) {
t = 1;
} else if (!boxChecked) {
t = 0;
}
});
widget.callBack();
},
),
// ),
);
}
}

Consumer not updating the state?

I am trying to create an Icon with a number indicator on top of it and the number indicator receives its data via a Consumer provider. The problem is that the state is not being updated by the consumer function and I don't understand why (if I update the state with a hot reload everything works just fine).
Here is the code for my main file:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => TestData())
// I use more providers but deleted them here for brevity
],
child: TestScreen3(),
),
);
}
}
The test screen 3 widget
class TestScreen3 extends StatefulWidget {
#override
_TestScreen3State createState() => _TestScreen3State();
}
class _TestScreen3State extends State<TestScreen3> {
#override
Widget build(BuildContext context) {
final testData = Provider.of<TestData>(context);
return Scaffold(
appBar: AppBar(
title: Text('Test app 3'),
actions: [
Consumer<TestData>(builder: (_, data, __) {
return IconButton(
icon: Badge(num: data.items.length.toString()),
onPressed: () => print(data.items.length));
})
],
),
body: Center(
child: ElevatedButton(
child: Text('Increase'),
onPressed: () {
testData.addItem();
},
),
),
);
}
}
The badge widget
class Badge extends StatelessWidget {
Badge({#required this.num});
final String num;
#override
Widget build(BuildContext context) {
return Stack(
children: [
Icon(Icons.assessment),
Positioned(
child: Container(
padding: EdgeInsets.all(2),
child: Text(
num,
style: TextStyle(fontSize: 8),
textAlign: TextAlign.center,
),
constraints: BoxConstraints(
minHeight: 12,
minWidth: 12,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.red,
),
),
),
],
);
}
}
and the data model I am using
class Item {
Item(this.id);
final String id;
}
class TestData with ChangeNotifier {
List<Item> _items = [];
List<Item> get items => [..._items];
void addItem() {
_items.add(Item(DateTime.now().toString()));
}
notifyListeners();
}
The imports work just fine, I left them out for brevity. I followed along a this tutorial: https://www.udemy.com/course/learn-flutter-dart-to-build-ios-android-apps/ and it uses a key argument for the badge that looks like this:
class Badge extends StatelessWidget {
const Badge({
Key key,
#required this.child,
#required this.value,
this.color,
}) : super(key: key);
final Widget child;
final String value;
final Color color;
However, the use of key or super is not explained in the tutorial and when I add these parameters to my code they don't seem to make a change.
Many thanks in advance, I probably missed something super obvious...
Add notifyListeners(); inside addItem() method
void addItem() {
_items.add(Item(DateTime.now().toString()));
notifyListeners();
}