help me figure out how to make the list update immediately after adding values (pressing the ElevatedButton - Navigator.of(context).pop();
).
I have this code in the main file:
import 'package:flutter/material.dart';
import 'data.dart';
void main() {
runApp(const MaterialApp(home: HomeScreen()));
}
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: const Color(0xff313131),
body: ListView.builder(
shrinkWrap: true,
itemCount: tasks.length,
itemBuilder: (context, index) {
var task = tasks[index];
return ListTile(
title: Text(
tasks[index].taskName,
style: const TextStyle(color: Colors.white),
),
subtitle: Row(
children: [
task.tagOne,
task.tagTwo,
],
),
);
}),
floatingActionButton: FloatingActionButton(
child: const Text('Add'),
onPressed: () {
showDialog(context: context, builder: (context) => AlertClass());
},
),
),
);
}
}
class AlertClass extends StatefulWidget {
const AlertClass({Key? key}) : super(key: key);
@override
State<AlertClass> createState() => _AlertClassState();
}
class _AlertClassState extends State<AlertClass> {
late String _textValue;
late bool _active;
@override
void initState() {
_active = false;
_textValue = 'Empty';
super.initState();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
content: TextField(onChanged: (String value) {
_textValue = value;
}),
actions: [
TextButton(
onPressed: () {
setState(() {
_active = !_active;
});
},
child: _active ? tagOneContainer[0] : tagOneContainer[1],
),
ElevatedButton(
onPressed: () {
setState(() {
tasks.addAll({
TaskData(
taskName: _textValue,
tagOne:
_active ? tagOneContainer[0] : tagOneContainer[1],
tagTwo: tagTwoContainer[0]),
});
});
Navigator.of(context).pop();
},
child: const Icon(Icons.add)),
],
);
}
}
Essentially, when you click the ElevatedButton Alert should close and the list is updated, but it is not. The list is only updated if you click on HotReload in Android Studio. The tasks and other variables are taken from another file.
CodePudding user response:
You can do await to your showDialog Widget. If it returns true, you can setState in your HomeScreen Class.
See this code:
bool result = await showDialog(context: context, builder: (context) => AlertClass());
if (result== true) {
setState(() {
});
}
Then in your ElevatedButton in AlertClass, pop with true parameter.
ElevatedButton(
onPressed: () {
setState(() {
tasks.addAll({
TaskData(
taskName: _textValue,
tagOne:
_active ? tagOneContainer[0] : tagOneContainer[1],
tagTwo: tagTwoContainer[0]),
});
});
Navigator.of(context).pop(true);//This will change the state
//of your homescreen class.
},
child: const Icon(Icons.add)),