Passing variables from Tab to DefaultTabController - Flutter - flutter

I have a DefaultTabController with two pages nested in a scaffold. In my scaffold's App Bar is a save button and I want this button to return a value to a previous page, based on a variable that is calculated in one of the tabs. How do I get this value?
Here is my DefaultTabController
DefaultTabController(
initialIndex: index,
length: 2,
child: Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
appBar: AppBar(
elevation: 0,
backgroundColor: fumigruen_accent,
leading: CloseButton(
color: Colors.black,
onPressed: () {
Navigator.of(context).pop();
},
),
actions: buildEditingActions(),
),
body: Column(children: [
tabBar(),
Expanded(
child: TabBarView(children: [
//1st Tab
GewichtsrechnerEinfach(),
//2nd Tab
Column()
]),
)
]),
));}
And here is the save-Button I want to use to pass a varaible to the previous screen
List<Widget> buildEditingActions() => [
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: fumigruen_accent,
elevation: 0,
foregroundColor: Colors.black,
),
onPressed: () {
Navigator.of(context).pop(gewicht);
},
icon: Icon(Icons.save),
label: Text("Speichern"))
];
The tabbar Code
Widget tabBar() => TabBar(
labelColor: Theme.of(context).primaryColor,
indicatorColor: Theme.of(context).primaryColor,
labelStyle: TextStyle(fontWeight: FontWeight.bold),
tabs: [
Tab(
child: Row(mainAxisSize: MainAxisSize.min, children: [
Icon(
Icons.assessment_outlined,
),
SizedBox(
width: 5,
),
Text("Einfach")
]),
),
Tab(
child: Row(mainAxisSize: MainAxisSize.min, children: [
Icon(
Icons.addchart,
),
SizedBox(
width: 5,
),
Text("Fortgeschritten")
]),
),
]);
and an extract of the GewichtsrechnerEinfach():
class _GewichtsrechnerEinfachState extends State<GewichtsrechnerEinfach> {
final _formKey = GlobalKey<FormState>();
num koerperlaenge = 0;
num brustumfang = 0;
var _koerperlaengeControler = TextEditingController();
var _brustumfangControler = TextEditingController();
num gewicht = 0;
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//{two textinput fields setting the variables koerperlaenge and brustumfang are here}
Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.8,
decoration: ThemeHelper().buttonBoxDecoration(context),
child: ElevatedButton(
style: ThemeHelper().buttonStyle(),
child: Padding(
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
child: Text(
"berechnen".toUpperCase(),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
onPressed: () async {
if (_formKey.currentState!.validate()) {
setState(() {
gewicht = Gewichtskalkulator().einfach(
brustumfang.toDouble(),
koerperlaenge.toDouble());
});
}
}),
),
),
],
),
),
),
);
}
The variable "gewicht" is calculated and changed in the first tab "GewichtsrechnerEinfach". So how do I get the changed variable to this main screen so that I can use it while saving?
Thanks a lot :)

As I found out by chatting in comments section, you are changing a value in a Page and you want to use it in another pages or screen, this is why you should use StateManagement something like Provider.
As you said you need to change the gewicht variable and use it where ever you want.
step 1) please add provider: ^6.0.5 (or any version that is compatible) in your pubspec.yaml and call flutter pub get.
step 2) now you should create a provider class to make all the variables that you want to use everywhere, alive. please create a dart file named:
gewichtsrechner_einfach_provider.dart
step 3) now you should put these codes in you provider class:
import 'package:flutter/material.dart';
class GewichtsrechnerEinfachProvider extends ChangeNotifier{
num _gewicht = 0;
num get gewicht => _gewicht;
void setGewicht(num newGewicht){
_gewicht = newGewicht;
notifyListeners();
}
}
as you see _gewicht is private and you can use it alive entire your project.
step 4) you should add the provider to main.dart:
MultiProvider(
providers: [
// you are adding your provider
ListenableProvider.value(value: GewichtsrechnerEinfachProvider()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: ...........
),
);
step 5) now you should use its setter and getter of gewicht:
as you see in _GewichtsrechnerEinfachState you are setting the value and should do this by using Consumer:
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Consumer<GewichtsrechnerEinfachProvider>(//note this
builder: (context, gewichtsrechnerEinfachProvider ,child) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//{two textinput fields setting the variables koerperlaenge and brustumfang are here}
Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.8,
decoration: ThemeHelper().buttonBoxDecoration(context),
child: ElevatedButton(
style: ThemeHelper().buttonStyle(),
child: Padding(
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
child: Text(
"berechnen".toUpperCase(),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
onPressed: () async {
if (_formKey.currentState!.validate()) {
// and note this
gewichtsrechnerEinfachProvider.setGewicht(
Gewichtskalkulator().einfach(
brustumfang.toDouble(),
koerperlaenge.toDouble())
);
}
}),
),
),
],
),
);
}
),
),
);
}
step 6) now you should use its getter where ever you want:
List<Widget> buildEditingActions() => [
Consumer<GewichtsrechnerEinfachProvider>(
builder: (context, gewichtsrechnerEinfachProvider ,child) {
return ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: fumigruen_accent,
elevation: 0,
foregroundColor: Colors.black,
),
onPressed: () {
// Navigator.of(context).pop(gewicht);
print('here is your result:
${gewichtsrechnerEinfachProvider.gewicht}');
},
icon: Icon(Icons.save),
label: Text("Speichern"));
}
)
];
note that you can use your provider where ever you want even with this code not just consumer:
var gewichtsrechnerEinfachProvider = Provider.of<GewichtsrechnerEinfachProvider>(context,listen: false);
as you see by changing its value the provider notifies to where you are showing it.
Ich hoffe, ich konnte dir helfen ;)
happy coding my friend...

Related

Flutter how to add a dialog screen over main screen like this

Hi all,
I would like to add a screen that slowly appears form the bottom or the screen and partially covers the main screen below. So you can still see the top part of the main screen. Does anyone know how to do this?
Thank you very much
for this you can use showModalBottomSheet method the simple example is
import 'package:flutter/material.dart';
void main() => runApp(const BottomSheetApp());
class BottomSheetApp extends StatelessWidget {
const BottomSheetApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Bottom Sheet Sample')),
body: const BottomSheetExample(),
),
);
}
}
class BottomSheetExample extends StatelessWidget {
const BottomSheetExample({super.key});
#override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
child: const Text('showModalBottomSheet'),
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return Container(
height: 200,
color: Colors.amber,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Modal BottomSheet'),
ElevatedButton(
child: const Text('Close BottomSheet'),
onPressed: () => Navigator.pop(context),
),
],
),
),
);
},
);
},
),
);
}
}
you can read more about this method here
You can use showModalBottomSheet() same as below...
showModalBottomSheet<void>(
// context and builder are
// required properties in this widget
context: context,
builder: (BuildContext context) {
// we set up a container inside which
// we create center column and display text
// Returning SizedBox instead of a Container
return SizedBox(
height: MediaQuery.of(context).size.height * 0.6,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Text('HERE You'll add all your content'),
],
),
),
);
},
);
You can call above method in
initState() of screen or buttons onPressed or onTap.
As per your shared Image I have try something like that Using ModalBottomSheet
Your Button Widget
ElevatedButton(
child: const Text('Show Modal BottomSheet'),
onPressed: () {
showModalBottomSheet<void>(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(25.0)),
),
context: context,
builder: (BuildContext context) {
return modelSheet(context);
},
);
},
)
bottomSheet Widget:
modelSheet(BuildContext context) {
return Container(
padding: const EdgeInsets.all(12),
decoration: const BoxDecoration(
borderRadius: BorderRadius.vertical(top: Radius.circular(25.0)),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Icon(
Icons.hourglass_empty_outlined,
color: Colors.red,
size: 40,
),
const SizedBox(
height: 10,
),
const Text(
'Beta version',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
const SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(
Icons.check,
color: Colors.red,
),
Text('better price')
],
),
const SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(
Icons.check,
color: Colors.red,
),
Text('early access')
],
),
const SizedBox(
height: 20,
),
RichText(
text: const TextSpan(
text:
'Please mind that this is a beta version of the app. As a founding member you can get',
style: TextStyle(fontSize: 20, color: Colors.black),
children: <TextSpan>[
TextSpan(
text: '50% off',
style: TextStyle(fontWeight: FontWeight.bold)),
TextSpan(text: ' the price & early access. !'),
],
),
),
const SizedBox(
height: 20,
),
const Text(
'You can look forward to more teachers and practices very soon.'),
const SizedBox(
height: 20,
),
ElevatedButton(
onPressed: () => Navigator.pop(context),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
fixedSize: const Size(double.maxFinite, 50)),
child: const Text('Got it'),
),
],
),
),
);
}
Result Screen->

DropdownButton<List> using local data - Do not list items on the screen, only after hot reload

I'm new to the flutter and I don't know how to solve this problem.
I have a List with await method, but my screen does not await for the list to load to list, only when I update with the hot-reload, the screen works.
My async method
ListaRefeitorio? _selecione;
List<ListaRefeitorio> _refeitorios = <ListaRefeitorio>[];
RefeitorioController controller = new RefeitorioController();
#override
void initState() {
super.initState();
_listarRefeitorios();
}
My Screen
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBarControleAcessoWidget("Refeitório"),
body: Column(
children: [
SizedBox(height: 30),
Container(
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
padding: EdgeInsets.only(left: 16, right: 16),
decoration: BoxDecoration(
border:
Border.all(color: AppColors.chartSecondary, width: 1),
borderRadius: BorderRadius.circular(15),
),
child: DropdownButton<ListaRefeitorio>(
hint: Text("Selecione Refeitório"),
dropdownColor: AppColors.white,
icon: Icon(Icons.arrow_drop_down),
iconSize: 36,
isExpanded: true,
underline: SizedBox(),
style: TextStyle(
color: AppColors.black,
fontSize: 20,
),
value: _selecione,
onChanged: (ListaRefeitorio? novoValor) {
setState(() {
_selecione = novoValor;
});
},
items: _refeitorios.map((ListaRefeitorio valueItem) {
return new DropdownMenuItem<ListaRefeitorio>(
value: valueItem,
child: new Text(valueItem.acessoPontoAcessoDescricao),
);
}).toList(),
),
),
),
),
),
Container(),
Expanded(
child: GridView.count(
crossAxisSpacing: 12,
mainAxisSpacing: 12,
crossAxisCount: 2,
children: [
Container(
child: SizedBox.expand(
child: FlatButton(
child: CardsWidget(
label: "Ler QR Code",
imagem: AppImages.scanQrCode,
),
onPressed: () {
scanQRCode();
},
),
),
),
Container(
child: SizedBox.expand(
child: FlatButton(
child: CardsWidget(
label: "Sincronizar Dados", imagem: AppImages.sync),
onPressed: () {
controller.sincronizar();
// RefeitorioService.listarRefeitorio();
},
),
),
),
SizedBox(height: 30),
Text("Resultado"),
Text(QRCode),
Text(DataHora),
Text(_selecione.toString()),
],
),
),
],
));
}
I've tried using the futurebuilder but I don't think that's my problem.
I don't know what to do anymore
I had the same issue with the DropDownButton list only displaying because of the Hot Reload refreshing the state.
When using a custom mapping of a List remember to use setState() in the method that populates the List with data (in my case it was pulling from Sqflite).
//This populate method would be called in either initstate or afterFirstLayout
populateDataList() {
await controller.getList().then((list) =>
setState(() {
_refeitorios = list;
})
);
}

How to create an admin UI left menu with Flutter [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm new to flutter but I have a curiosity. Considering the typical bootstrap admin UI that you can find online and the typical left menu, how would you recreate that with flutter? I'm particularly interested on a left menu that can be resized clicking on a button and on a sub-menu that can appear and disappear.
An example can be found here
Edit:
I want to be be clear about the effect I'm trying to reproduce as well. If you click the link relative to the example on the left you see a number of menu. For instance, clicking on Base you are going to see a vertical menu appearing and disappearing. I would like to know how to reproduce it as well.
Thanks
Thanks
I have tried to re-create the same design with some minor changes in Flutter. I have to enable flutter web support by following the instructions here:
Flutter Web
Regarding the left menu, I have used AnimatedSize widget to give the sliding drawer feel & placed it inside Row.
Please find the code below:
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatefulWidget {
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget>
with SingleTickerProviderStateMixin {
final colors = <Color>[Colors.indigo, Colors.blue, Colors.orange, Colors.red];
double _size = 250.0;
bool _large = true;
void _updateSize() {
setState(() {
_size = _large ? 250.0 : 0.0;
_large = !_large;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: [
AnimatedSize(
curve: Curves.easeIn,
vsync: this,
duration: Duration(seconds: 1),
child: LeftDrawer(size: _size)),
Expanded(
flex: 4,
child: Container(
child: Column(
children: [
Container(
color: Colors.white,
padding: const EdgeInsets.all(8),
child: Row(
children: [
IconButton(
icon: Icon(Icons.menu, color: Colors.black87),
onPressed: () {
_updateSize();
},
),
FlatButton(
child: Text(
'Dashboard',
style: const TextStyle(color: Colors.black87),
),
onPressed: () {},
),
FlatButton(
child: Text(
'User',
style: const TextStyle(color: Colors.black87),
),
onPressed: () {},
),
FlatButton(
child: Text(
'Settings',
style: const TextStyle(color: Colors.black87),
),
onPressed: () {},
),
const Spacer(),
IconButton(
icon: Icon(Icons.brightness_3, color: Colors.black87),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.notification_important,
color: Colors.black87),
onPressed: () {},
),
CircleAvatar(),
],
),
),
Container(
height: 1,
color: Colors.black12,
),
Card(
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0),
),
child: Container(
color: Colors.white,
padding: const EdgeInsets.all(20),
child: Row(
children: [
Text(
'Home / Admin / Dashboard',
style: const TextStyle(color: Colors.black),
),
],
),
),
),
Expanded(
child: ListView(
children: [
Row(
children: [
_container(0),
_container(1),
_container(2),
_container(3),
],
),
Container(
height: 400,
color: Color(0xFFE7E7E7),
padding: const EdgeInsets.all(16),
child: Card(
color: Colors.white,
child: Container(
padding: const EdgeInsets.all(16),
child: Text(
'Traffic',
style: const TextStyle(color: Colors.black87),
),
),
),
),
],
),
),
],
),
),
),
],
),
);
}
Widget _container(int index) {
return Expanded(
child: Container(
padding: const EdgeInsets.all(20),
color: Color(0xFFE7E7E7),
child: Card(
color: Color(0xFFE7E7E7),
child: Container(
color: colors[index],
width: 250,
height: 140,
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(
'9.823',
style: TextStyle(fontSize: 24),
)),
Icon(Icons.more_vert),
],
),
Text('Members online')
],
),
),
),
),
);
}
}
class LeftDrawer extends StatelessWidget {
const LeftDrawer({
Key key,
this.size,
}) : super(key: key);
final double size;
#override
Widget build(BuildContext context) {
return Expanded(
flex: 1,
child: Container(
width: size,
color: const Color(0xFF2C3C56),
child: ListView(
children: [
Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(16),
color: Color(0xFF223047),
child: Text('CORE UI'),
),
_tile('Dashboard'),
Container(
padding: const EdgeInsets.only(left: 10),
margin: const EdgeInsets.only(top: 30),
child: Text('THEME',
style: TextStyle(
color: Colors.white54,
))),
_tile('Colors'),
_tile('Typography'),
_tile('Base'),
_tile('Buttons'),
],
),
),
);
}
Widget _tile(String label) {
return ListTile(
title: Text(label),
onTap: () {},
);
}
}
You can use the Drawer widget inside a Scaffold. If you want the navigation drawer to be able to resize according to the browser height and width you can use the responsive_scaffold package.

ListTile key not found in Flutter

I have a List defined as below and I'm trying to highlight one element of the list during the tutorial. I am currently using Tutorial Coach Mark. Every time I debug my app it shows me
KEY information could not be obtained
I don't know why this is happening as I've followed all the necessary steps for integration shown in the dependency.
This is my code:
class _SettingsState extends State<Settings> {
TutorialCoachMark tutorialCoachMark;
GlobalKey keyButton3 = GlobalKey();
List<TargetFocus> targets = List();
void initState() {
initTarget();
WidgetsBinding.instance.addPostFrameCallback(_afterLayouts);
super.initState();
}
void _afterLayouts(_) {
Future.delayed(Duration(milliseconds: 100), () {
showTutorial(context);
});
}
void showTutorial(context) {
tutorialCoachMark = TutorialCoachMark(context,
targets: targets,
colorShadow: Colors.red,
textSkip: "SKIP",
paddingFocus: 10,
opacityShadow: 0.8, onFinish: () {
print("finish");
}, onClickTarget: (target) {
print(target);
}, onClickSkip: () {
print("skip");
})
..show();
}
void initTarget() {
targets.add(
TargetFocus(
//claim reward
identify: "Target 2",
keyTarget: keyButton3,
color: Colors.purple,
contents: [
ContentTarget(
align: AlignContent.bottom,
child: Container(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Click here",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 20.0),
),
],
),
))
],
shape: ShapeLightFocus.RRect,
radius: 6),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
iconTheme: IconThemeData(
color: Colors.white,
),
elevation: 0,
title: Text(
'Settings',
style: kTasksStyle,
),
backgroundColor: Color(0xff0C7368),
),
body: Stack(
children: [
Padding(
padding: const EdgeInsets.only(top: 8),
child: ListView.separated(
separatorBuilder: (context, index) => Divider(
height: 2,
color: Colors.grey.withOpacity(0.3),
),
itemCount: 5,
itemBuilder: (context, index) {
return Padding(
padding: EdgeInsets.all(5.0),
child: ListTile(
key: index == 0 ? keyButton3 : null,// to highlight the 0th index of the list only
title: Text(
"Hello",
style: kTasksStyle.copyWith(
fontSize: 15,
color: Colors.black,
fontWeight: FontWeight.normal),
),
leading: Icon(
Icons.supervised_user_circle,
color: Color(0xff0C7368),
),
),
);
}),
)
],
));
}
}
I am trying to achieve something similar to this:

Problem with List builder repeat the data when adding or removing item in the list

I'm new to flutter. When I adding new item or removing an item from the list, the list builder does update the list, but the problem is that the list builder also displaying the previous item list and showing new updated item list. So what I want to do is keeping the new updated item list instead of old item list.
class AlarmPage extends StatefulWidget {
final String title;
AlarmPage({Key key, this.title}) : super(key: key);
#override
_AlarmPageState createState() => _AlarmPageState();
}
class _AlarmPageState extends State<AlarmPage> {
String alarmName;
// Test Function
void _addAlarm() {
setState(() {
Navigator.push(
context, MaterialPageRoute(builder: (context) => AddAlarm()));
});
}
#override
void initState() {
super.initState();
Provider.of<AlarmsProvider>(context, listen: false).getLocalStorage();
}
#override
Widget build(BuildContext context) {
List<Widget> allWidgetsAlarms = List<Widget>();
return Consumer<AlarmsProvider>(builder: (context, alarmProviderItem, _) {
List<String> localAlarms = alarmProviderItem.alarms;
if (localAlarms != null) {
localAlarms.forEach((item) {
allWidgetsAlarms.add(
Stack(
children: <Widget>[
InkWell(
child: Container(
color: Color(0xff212121),
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
// Alarm Name & Title
Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(width: 2),
)),
child: Row(
children: <Widget>[
Icon(Icons.alarm, color: Colors.yellow),
SizedBox(width: 20.0),
Text('$item',
style: TextStyle(
color: Color(0xffC1C1C1),
fontSize: 15.0,
fontWeight: FontWeight.w900)),
SizedBox(height: 5),
],
),
),
SizedBox(height: 10),
// Alarm Time & Toggle Switch
Container(
child: Row(
children: <Widget>[
Text(
'Time',
style: TextStyle(
fontSize: 30, color: Colors.white),
),
SizedBox(width: 20),
Text(
'AM / PM',
style: TextStyle(
fontSize: 20, color: Color(0xffB5B5B5)),
),
SizedBox(width: 150),
Icon(Icons.switch_camera, color: Colors.yellow),
],
),
),
// Alarm Repeat
Container(
child: Row(children: <Widget>[
Text(
'Repeat',
style: TextStyle(
fontSize: 11, color: Color(0xff616161)),
),
Container(
child: DaySelector(
value: null,
onChange: (value) {},
color: Colors.yellow[400],
mode: DaySelector.modeFull,
),
),
]),
),
],
),
),
onLongPress: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddAlarm(item: item)));
},
),
SizedBox(height: 180),
],
),
);
print(item);
});
}
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
title: Text('Azy Alarm'),
centerTitle: true,
),
body: Container(
decoration: BoxDecoration(
image: const DecorationImage(
fit: BoxFit.cover,
image: AssetImage('assets/images/background_image(dark).png')),
),
// child: ListView(children: allWidgetsAlarms),
child: ListView.builder(
itemCount: allWidgetsAlarms.length,
padding: const EdgeInsets.all(8.0),
itemBuilder: (BuildContext context, int index) {
return allWidgetsAlarms[index];
}),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
backgroundColor: Colors.blue,
elevation: 0,
onPressed: _addAlarm,
),
);
});
}
}
So I think your issue is this line: allWidgetsAlarms.add( You construct allWidgetsAlarms in your builder, but the builder is not called again every time you Consumer rebuilds, hence it is just appending the new contents to the end of the list. To fix this, keep your original initialization of allWidgetsAlarms just at the top of the builder in your Consumer, add the following line:
allWidgetsAlarms = List<Widget>();
This will resert allWidgetsAlarms. Hope it helps!