Home > Back-end >  Flutter button doesn't work when passing variables between files
Flutter button doesn't work when passing variables between files

Time:09-09

I'm building a workout app with a sign out button and a delete exercise button. I've made a single file instead of 2 and passed variable. I did this so That I don't have to make 2 files.

the problem is with function; in the onPressed call back in dialog.instance.dart

if I don't pass the variables it works fine. but I don't wanna make 2 separate files.

I tried this but it didn't work to plan:

dialog_instance.dart

Future<void> DialogInstance(BuildContext context, void Function()? function,
    String name, String description) {
  return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          backgroundColor: Colors.blueGrey,
          title: Text(
            name,
            style: const TextStyle(color: Colors.white),
          ),
          actions: [
            Row(
              children: [
                const SizedBox(width: 16.0),
                Text(
                  'Are you sure $description',
                  style: const TextStyle(color: Colors.white),
                )
              ],
            ),
            const SizedBox(height: 20),
            Row(
              children: [
                Expanded(
                  child: OutlinedButton(
                    onPressed: () {
                      function;
                    },
                    style:
                        OutlinedButton.styleFrom(backgroundColor: Colors.red),
                    child: const Text('Yes',
                        style: TextStyle(color: Colors.white)),
                  ),
                ),
              ],
            ),
            Row(
              children: [
                Expanded(
                  child: OutlinedButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: const Text('Cancel',
                        style: TextStyle(color: Colors.white)),
                  ),
                ),
              ],
            ),
          ],
        );
      });
}

workout_page.dart

class WorkoutPage extends StatefulWidget {
  const WorkoutPage({Key? key}) : super(key: key);

  @override
  State<WorkoutPage> createState() => _WorkoutPageState();
}

User user = FirebaseAuth.instance.currentUser!;
String signOutText = 'Sign Out';
const signOutDescription = 'you want to sign out?';

class _WorkoutPageState extends State<WorkoutPage> {
  @override
  Widget build(BuildContext context) {
    void signOutFunction() {
      AuthService.signOutMethod();
      Navigator.of(context)
          .pushNamedAndRemoveUntil('/login', (Route<dynamic> route) => false);
    }

    return Scaffold(
      backgroundColor: backgroundColor,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text(user.email!, style: const TextStyle(fontSize: 14)),
        backgroundColor: backgroundColor,
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: GradientElevatedButton(
                onPressed: () {
                  DialogInstance(context, signOutFunction, signOutText,
                      signOutDescription);
                },
                child: const Text('Sign out')),
          )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.cyan,
        onPressed: () {
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => const ExercisePage()));
        },
        child: const Icon(
          Icons.add,
          color: Colors.black,
        ),
      ),
    );
  }
}

cardiovascular_card.dart

class CardiovascularCard extends StatefulWidget {
  AsyncSnapshot<QuerySnapshot> snapshot;
  int index;
  CardiovascularCard(this.snapshot, this.index, {Key? key}) : super(key: key);

  @override
  State<CardiovascularCard> createState() => _CardiovascularCardState();
}

String deleteExerciseText = 'Delete exercise';
final uid = FirebaseAuth.instance.currentUser?.uid;
TextEditingController _calorieController = TextEditingController();
TextEditingController _timeController = TextEditingController();
String deleteExerciseDescription = 'you want to delete this exercise?';

class _CardiovascularCardState extends State<CardiovascularCard> {
  @override
  Widget build(BuildContext context) {
    String deleteExerciseText = 'Delete exercise';
    final uid = FirebaseAuth.instance.currentUser?.uid;
    final data = widget.snapshot.data;
    final exerciseId = data!.docs[widget.index].reference.id;
    void deleteExerciseFunction() {
      FirebaseFirestore.instance
          .runTransaction((Transaction myTransaction) async {
        myTransaction.delete(data.docs[widget.index].reference);
      });
    }

    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(children: [
        Card(
          elevation: 8,
          color: const Color.fromARGB(255, 81, 108, 122),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      data.docs[widget.index]['exerciseName'],
                      style: const TextStyle(
                          fontSize: 20.0, fontWeight: FontWeight.bold),
                    ),
                  ),
                  const Divider(thickness: 1.0),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: const [
                  Text(
                    'Calories',
                    style: TextStyle(color: Colors.white),
                  ),
                  Text(
                    'Time',
                    style: TextStyle(color: Colors.white),
                  ),
                ],
              ),
              Slidable(
                endActionPane: ActionPane(
                  motion: const ScrollMotion(),
                  children: [
                    SlidableAction(
                      onPressed: (context) {
                        DialogInstance(context, deleteExerciseFunction,
                            deleteExerciseText, deleteExerciseDescription);
                      },
                      label: 'Delete',
                      backgroundColor: Colors.red,
                      icon: Icons.delete,
                    )
                  ],
                ),
                child: ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.145,
                        child: TextField(
                          style: const TextStyle(fontWeight: FontWeight.bold),
                          cursorColor: Colors.white,
                          onSubmitted: (value) async {
                            FirebaseFirestore.instance.runTransaction(
                                (Transaction myTransaction) async {
                              FirebaseFirestore.instance
                                  .collection('users')
                                  .doc(uid)
                                  .collection('workout')
                                  .doc(exerciseId)
                                  .update({'caloriesBurnt': value});
                            });
                          },
                          textAlign: TextAlign.center,
                          keyboardType: TextInputType.number,
                          controller: _calorieController,
                          decoration: InputDecoration(
                              focusedBorder: const UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                              ),
                              hintText: data.docs[widget.index]['caloriesBurnt']
                                  .toString()),
                        ),
                      ),
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.145,
                        child: TextField(
                          style: const TextStyle(fontWeight: FontWeight.bold),
                          cursorColor: Colors.white,
                          onSubmitted: (value) async {
                            FirebaseFirestore.instance.runTransaction(
                                (Transaction myTransaction) async {
                              FirebaseFirestore.instance
                                  .collection('users')
                                  .doc(uid)
                                  .collection('workout')
                                  .doc(exerciseId)
                                  .update({'time': value});
                            });
                          },
                          textAlign: TextAlign.center,
                          keyboardType: TextInputType.number,
                          controller: _timeController,
                          decoration: InputDecoration(
                              focusedBorder: const UnderlineInputBorder(
                                borderSide: BorderSide(color: Colors.white),
                              ),
                              hintText:
                                  data.docs[widget.index]['time'].toString()),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ]),
    );
  }
}

CodePudding user response:

If i understand correctly - function named function is not called.

You have to call the function with function() or tear-off

 Row(
   children: [ 
      Expanded(
         child: OutlinedButton(
            onPressed: () {
              function();
            },

or

 Row(
   children: [ 
      Expanded(
         child: OutlinedButton(
            onPressed:function,
  • Related