skip to Main Content

setState function in the custom_dialog page dosen’t work

in this code, I want to show a list of customers with a specific data for each customer. The issue is when I want to add a new customer through the floating action button that’s showing dialog1 from the custom_dialog page, the customer is added to the list but does not appear in in the page

main page code:

import 'package:flutter/material.dart';
import 'package:untitled66/custom_dialog.dart';
import 'package:untitled66/customers.dart';

List<Customers> customersList = [
  Customers(
    name: 'munsef',
    itemName: 'mobile',
    price: 100,
    profit: 30,
    period: 12,
    key: UniqueKey(),
  ),
];

void main() {
  runApp(const MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          floatingActionButton: FloatingActionButton(
              child: Icon(Icons.add),
              onPressed: () {
                showDialog(
                    context: context,
                    builder: (context) {
                      return Dialog1();
                    });
              }),
          appBar: AppBar(
            title: Text('List of Items'),
            backgroundColor: Colors.lightBlue,
          ),
          body: ListView.builder(
              itemCount: customersList.length,
              itemBuilder: (element, index) {
                return InkWell(
                  child: Card(
                    child: customersList[index],
                  ),
                  onLongPress: () {
                    customersList.removeAt(index);
                    setState(() {});
                  },
                  
                );
              })),
    );
     }
     }

custome_dialog page:

import 'package:flutter/material.dart';
import 'package:untitled66/customers.dart';
import 'package:untitled66/main.dart';

class Dialog1 extends StatefulWidget {
  Dialog1({super.key});

  @override
  State<StatefulWidget> createState() {
    return dialog1State();
  }
}

class dialog1State extends State<Dialog1> {
  final TextEditingController customerNamecontr = TextEditingController();
  final TextEditingController itemNamecontr = TextEditingController();
  final TextEditingController pricecontr = TextEditingController();
  final TextEditingController profitcontr = TextEditingController();
  final TextEditingController periodcontr = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text('Add customer'),
      content: Form(
          child: ListView(
        children: [
          Text("Customer's name:"),
          TextFormField(
            controller: customerNamecontr,
          ),
          Text("Item's name:"),
          TextFormField(
            controller: itemNamecontr,
          ),
          Text("Price:"),
          TextFormField(
            controller: pricecontr,
          ),
          Text("Profit:"),
          TextFormField(
            controller: profitcontr,
          ),
          Text("Period:"),
          TextFormField(
            controller: periodcontr,
          ),
        ],
      )),
      actions: [
        TextButton(
            onPressed: () {
              double? price = double.tryParse(pricecontr.text);
              int? profit = int.tryParse(profitcontr.text);
              int? period = int.tryParse(periodcontr.text);
              customersList.add(Customers(
                name: customerNamecontr.text,
                itemName: itemNamecontr.text,
                price: price!,
                profit: profit!,
                period: period!,
                key: UniqueKey(),
              ));
              setState(() {});
              Navigator.of(context).pop();
            },
            child: Text('Add'))
      ],
    );
  }
}

2

Answers


  1. You are calling set state in the context of the dialog what you need to do is to call the set state in the context of the list view , modify your dialog to

    import 'package:flutter/material.dart';
    import 'package:untitled66/customers.dart';
    import 'package:untitled66/main.dart';
    
    class Dialog1 extends StatefulWidget {
        Dialog1({super.key, required this.refresh});
        final Function refresh;
    
      @override
      State<StatefulWidget> createState() {
        return dialog1State();
      }
    }
    
    class dialog1State extends State<Dialog1> {
      final TextEditingController customerNamecontr = TextEditingController();
      final TextEditingController itemNamecontr = TextEditingController();
      final TextEditingController pricecontr = TextEditingController();
      final TextEditingController profitcontr = TextEditingController();
      final TextEditingController periodcontr = TextEditingController();
      @override
      Widget build(BuildContext context) {
        return AlertDialog(
          title: Text('Add customer'),
          content: Form(
              child: ListView(
            children: [
              Text("Customer's name:"),
              TextFormField(
                controller: customerNamecontr,
              ),
              Text("Item's name:"),
              TextFormField(
                controller: itemNamecontr,
              ),
              Text("Price:"),
              TextFormField(
                controller: pricecontr,
              ),
              Text("Profit:"),
              TextFormField(
                controller: profitcontr,
              ),
              Text("Period:"),
              TextFormField(
                controller: periodcontr,
              ),
            ],
          )),
          actions: [
            TextButton(
                onPressed: () {
                  double? price = double.tryParse(pricecontr.text);
                  int? profit = int.tryParse(profitcontr.text);
                  int? period = int.tryParse(periodcontr.text);
                  customersList.add(Customers(
                    name: customerNamecontr.text,
                    itemName: itemNamecontr.text,
                    price: price!,
                    profit: profit!,
                    period: period!,
                    key: UniqueKey(),
                  ));
                  widget.refresh();
                  Navigator.of(context).pop();
                },
                child: Text('Add'))
          ],
        );
      }
    }
    

    and modify your main to

    import 'package:flutter/material.dart';
    import 'package:untitled66/custom_dialog.dart';
    import 'package:untitled66/customers.dart';
    
    List<Customers> customersList = [
      Customers(
        name: 'munsef',
        itemName: 'mobile',
        price: 100,
        profit: 30,
        period: 12,
        key: UniqueKey(),
      ),
    ];
    
    void main() {
      runApp(const MaterialApp(
        home: MyApp(),
      ));
    }
    
    class MyApp extends StatefulWidget {
      const MyApp({super.key});
    
      @override
      State<MyApp> createState() => MyAppState();
    }
    
    class MyAppState extends State<MyApp> {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
              floatingActionButton: FloatingActionButton(
                  child: Icon(Icons.add),
                  onPressed: () {
                    showDialog(
                        context: context,
                        builder: (context) {
                          return Dialog1(refresh: () {
                        setState(() {});
                      });
                        });
                  }),
              appBar: AppBar(
                title: Text('List of Items'),
                backgroundColor: Colors.lightBlue,
              ),
              body: ListView.builder(
                  itemCount: customersList.length,
                  itemBuilder: (element, index) {
                    return InkWell(
                      child: Card(
                        child: customersList[index],
                      ),
                      onLongPress: () {
                        customersList.removeAt(index);
                        setState(() {});
                      },
                      
                    );
                  })),
        );
         }
         }
    

    this will cause your child dialog to call the set state in ths context of its parent

    Login or Signup to reply.
  2. You have to create a function to add new customer in MyAppState class and pass that to Dialog1
    Example:

    import 'package:flutter/material.dart';
    
    
    import 'package:untitled66/custom_dialog.dart';
    import 'package:untitled66/customers.dart';
    
    List<Customers> customersList = [
      Customers(
        name: 'munsef',
        itemName: 'mobile',
        price: 100,
        profit: 30,
        period: 12,
        key: UniqueKey(),
      ),
    ];
    
    void main() {
      runApp(const MaterialApp(
        home: MyApp(),
      ));
    }
    
    class MyApp extends StatefulWidget {
      const MyApp({super.key});
      
      @override
      State<MyApp> createState() => MyAppState();
    }
    
    class MyAppState extends State<MyApp> {
    void addNewCustomer(Customers newCustomer){
          customersList.add(newCustomer);
          setState({});
      }
    
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
              floatingActionButton: FloatingActionButton(
                  child: Icon(Icons.add),
                  onPressed: () {
                    showDialog(
                        context: context,
                        builder: (context) {
                          return Dialog1(onTap:addNewCustomer);
                        });
                  }),
              appBar: AppBar(
                title: Text('List of Items'),
                backgroundColor: Colors.lightBlue,
              ),
              body: ListView.builder(
                  itemCount: customersList.length,
                  itemBuilder: (element, index) {
                    return InkWell(
                      child: Card(
                        child: customersList[index],
                      ),
                      onLongPress: () {
                        customersList.removeAt(index);
                        setState(() {});
                      },
                      
                    );
                  })),
        );
         }
         }
    

    And change your Dialog1 Widget to

    import 'package:flutter/material.dart';
    import 'package:untitled66/customers.dart';
    import 'package:untitled66/main.dart';
    
    class Dialog1 extends StatefulWidget {
        Dialog1({super.key, required this.onTap});
        final Function(Customers newCustomer) onTap;
    
      @override
      State<StatefulWidget> createState() {
        return dialog1State();
      }
    }
    
    class dialog1State extends State<Dialog1> {
      final TextEditingController customerNamecontr = TextEditingController();
      final TextEditingController itemNamecontr = TextEditingController();
      final TextEditingController pricecontr = TextEditingController();
      final TextEditingController profitcontr = TextEditingController();
      final TextEditingController periodcontr = TextEditingController();
      @override
      Widget build(BuildContext context) {
        return AlertDialog(
          title: Text('Add customer'),
          content: Form(
              child: ListView(
            children: [
              Text("Customer's name:"),
              TextFormField(
                controller: customerNamecontr,
              ),
              Text("Item's name:"),
              TextFormField(
                controller: itemNamecontr,
              ),
              Text("Price:"),
              TextFormField(
                controller: pricecontr,
              ),
              Text("Profit:"),
              TextFormField(
                controller: profitcontr,
              ),
              Text("Period:"),
              TextFormField(
                controller: periodcontr,
              ),
            ],
          )),
          actions: [
            TextButton(
                onPressed: () {
                  double? price = double.tryParse(pricecontr.text);
                  int? profit = int.tryParse(profitcontr.text);
                  int? period = int.tryParse(periodcontr.text);
                  onTap(Customers(name: ........)) // Add the customer here
                
                  Navigator.of(context).pop();
                },
                child: Text('Add'))
          ],
        );
      }
    
     }
    

    I am too bad at this, but i hope you understood 😊.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search