flutterbuttonstateflutter-onpressed

TextButton is automatically invoked when the dropDown menu item is changed


Here goes my code ,

I am using the TextButton to update the order ,But after every change in the dropdown item, onPress is automatically invoked and the function updateOrder is automatically invoked

import 'package:admin/constants/Constants.dart';
import 'package:admin/model/order_model.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';

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

  @override
  State<DetailsScreen> createState() => _DetailsScreenState();
}

class _DetailsScreenState extends State<DetailsScreen> {
  List<String> _dropDownQuantities = [Pending, Confirmed, Rejected, Success];

  late OrderModel order;
  late String selectedStatus = order.status;
  @override
  Widget build(BuildContext context) {
    order = ModalRoute.of(context)?.settings.arguments as OrderModel;

    return Scaffold(
        appBar: AppBar(
          actions: [],
          title: Text("Order Details"),
        ),
        body: Column(children: [
          Text(order.id),
          DropdownButtonHideUnderline(
              child: DropdownButton2<String>(
            value: selectedStatus,
            items: _dropDownQuantities
                .map((e) => DropdownMenuItem<String>(
                      child: Text(e),
                      value: e,
                    ))
                .toList(),
            onChanged: (value) {
              setState(() {
                selectedStatus = value;
              });
            },
          )),
          TextButton(onPressed: updateOrder(order, selectedStatus), child: Text("Confirm")),
          
        ]));
  }
}

updateOrder(OrderModel order, String selected) {
  print("I am executed");
}

So whenever i change the dropDown menu,

I am executed is printed in the console.

Edit:

But when i used the container with InkWell it was working fine. Why not working with TextButton ?


Solution

  • You are directly calling the method on build, you can create an inline anonymous function to handle this.

    TextButton(
        onPressed: ()=> updateOrder(order, selectedStatus),
        child: Text("Confirm")),
    

    onPressed Called when the button is tapped or otherwise activated.

    While we use onPressed:method() call on every build, on dropDown onChanged we use setState, and it rebuilds the UI and onPressed:method() call again.

    What we need here is to pass a function(VoidCallback) that will trigger while we tap on the button. We provide it like,

    onPressed:(){
       myMethod();
    }
    

    More about TextButton.