samedi 24 décembre 2022

Call function in class State for checked Checkbox from subclass in one file .dart

How to call function with setState for checked Checkbox from sub class in one file dart, i has tried like this but still eror, this is error ' [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: setState() called in constructor: _CustomerWgtFormState#a6d60(lifecycle state: created, no widget, not mounted) E/flutter ( 3739): This happens when you call setState() on a State object for a widget that hasn't been inserted into the widget tree yet. It is not necessary to call setState() in the constructor, since the state is already assumed to be dirty when it is initially created. '

eror ini line code //ERROOR //error in this line, while want to set Checkbox with true m.createState().changedWeek1(true);

these is my code

file class CustomerScreen.dart

import 'package:bubble_tab_indicator/bubble_tab_indicator.dart';
import 'package:flutter/material.dart';
import 'package:sfaf/view/widgatepage/wgtpage_customer/CustomerWgtForm.dart';
import 'package:sfaf/view/widgatepage/wgtpage_customer/CustomerWgtLV.dart';

void main() {
  runApp(CustomerScreen());
}
class CustomerScreen extends StatefulWidget {
  @override
  _CustomerScreenState createState() => _CustomerScreenState();
}

late TabController _tabController;

class _CustomerScreenState extends State<CustomerScreen> with TickerProviderStateMixin{

  late FocusNode myFocusNode;
  CustomerWgtForm _customerWgtForm=new CustomerWgtForm();
  CustomerWgtLV   _customerWgtLV =new CustomerWgtLV();


  @override
  void initState() {
    super.initState();
      _tabController = TabController(length: 2, vsync: this, initialIndex: 0,);
      _tabController.addListener(_handleTabSelection);
      myFocusNode = FocusNode();
      WidgetsBinding.instance.addPostFrameCallback((_) {
         FocusScope.of(context).requestFocus(myFocusNode);
      });
  }

  @override
  void dispose() {
    myFocusNode.dispose();
   _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            appBar: AppBar(
              title: Text("Customer"),
              elevation: 0.0,
              titleSpacing: 10.0,
              centerTitle: true,
              leading: InkWell(
                onTap: () {
                  Navigator.pop(context);
                },
                child: Icon(Icons.arrow_back_ios, color: Colors.black54,),
              ),
            ),
`
            body:Column(
               children:[
                   Container(
                     color: Colors.indigo, height: 50, width: 800,
                     margin: EdgeInsets.fromLTRB(0, 0, 0, 5),
                     child: TabBar(
                            controller: _tabController,
                         indicatorSize: TabBarIndicatorSize.tab,
                          isScrollable: true,
                  unselectedLabelColor: Colors.black,
                             indicator: BubbleTabIndicator(
                                    indicatorHeight: 48,
                                     indicatorColor: Colors.amber,
                tabBarIndicatorSize: TabBarIndicatorSize.tab,
                                    indicatorRadius: 5,
                             ),
                      tabs: [
                              Tab(icon :Image.asset("images/add_sign.png",),text:'Create Data'),
                              Tab(icon :Image.asset("images/list_go.png",),text:'List Data',)
                            ]
                            ),
                    ),
                    Expanded(
                      child: Container(
                               height: 900,
                               margin: EdgeInsets.fromLTRB(0, 0, 0, 5),
                                child: TabBarView(
                           controller: _tabController,
                             children: [
                                    _customerWgtForm,
                                    _customerWgtLV
                                 ]
                                )
                            )
                    )
                  ]
            )
            
        )
    );
  }
}
 //subclass
 class SelectedIndexTabbar{
    static setSelectedIndexTabbarCreateData(){
       _tabController.index=0;
    }
 }
`

file class CustomerWgtLV.dart
import 'package:flutter/material.dart';
import 'package:sfaf/database/entity/Customer.dart';
import 'package:sfaf/database/impl/CustomerImpl.dart';
import 'package:sfaf/view/widgatepage/wgtpage_customer/CustomerWgtForm.dart';

TextEditingController searchNameController = TextEditingController();

  List<Customer?>_getListCustomer=<Customer>[];
  Future _getListCustomerFromDB() async {
       Future<List<Customer?>>? listCustomer=null;
       if(searchNameController.text.isEmpty) {
            listCustomer = CustomerImpl().getListCustomerImpl();
       }
       else{
            listCustomer =   CustomerImpl().getListCustomerByCustNameImpl(searchNameController.text.toString());
       }
       List<Customer?> listnya = await listCustomer ;
       _getListCustomer=listnya;
  }

  class CustomerWgtLV extends StatefulWidget {
       @override
       _CustomerWgtLVState createState() => new _CustomerWgtLVState();
  }

class _CustomerWgtLVState extends State<CustomerWgtLV> {
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =  GlobalKey<RefreshIndicatorState>();
  Future<void> refreshListCustomers() async {
    setState(() {
        _getListCustomerFromDB();
    });
  }

  @override
  void initState() {
    refreshListCustomers();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
             key: _refreshIndicatorKey,
       onRefresh: () async  {
              _refreshIndicatorKey.currentState?.show();
               refreshListCustomers();
        },
        child: Scaffold(
            backgroundColor:  Colors.blueAccent,
            appBar: AppBar(
            title: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text("List Customers"),
                Expanded(
                  child: TextField(),
                ),
              ],
            ), 
          ),
        body: _buildCardDesign(),
      ),
    );

  }

  Widget _buildCardDesign() {
    return Container(
      margin: EdgeInsets.all(0),
      child: ListView.builder(
          itemCount: _getListCustomer.length,
          shrinkWrap: true,
          physics: const BouncingScrollPhysics(
          parent: AlwaysScrollableScrollPhysics()),
          scrollDirection: Axis.vertical,
          itemBuilder: (BuildContext context, int index) {
               var customer = _getListCustomer[index];
               return _buildCardView(customer);
          },
        ),
    );
  }

  Widget _buildCardView(Customer? customer) {
    return Container(
      width: MediaQuery.of(context).size.width,
      child: Container(
        margin: EdgeInsets.all(7),
        height: 120,
        width: MediaQuery.of(context).size.width,
        decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.all(Radius.circular(10))),
        padding: EdgeInsets.fromLTRB(10, 5, 2, 5),
        child: Stack(
          children: [
            Row(
              children: [
                ClipRRect(
                 borderRadius: BorderRadius.circular(10.0),
                        child: Image.asset('images/shop_on_ballon_36.png', height: 90.0 , width: 60.0, fit: BoxFit.cover,),
                ),
                Container(
                  padding: EdgeInsets.only(left: 10),
                    child: Column(crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                               Container(
                                  child: Text('${customer!.custCode} -  ${customer.custName}',
                                              style: TextStyle(color: Colors.black,fontWeight: FontWeight.bold,fontSize: 14), ),
                               ),
                            ]
                    ),
                ),
             ],
          ),
          Positioned(top: 80, left: 285,
           child:SizedBox( 
                  width: 80,height: 25,
                  child:ElevatedButton(
               style: ElevatedButton.styleFrom(
                  minimumSize: const Size.fromHeight(5),
                                    shape: RoundedRectangleBorder(
                             borderRadius: BorderRadius.circular(25),),
                elevation: 15.0,
                           ),
                           onPressed:() async {
                 //Call function getForUpdate in file CustomerWgtForm.dart 
                 //and this UpdateDataCust is Sub class from file CustomerWgtForm,
                             //getForUpdate this is static function
                 //when this execute/button Edit is clicked/tap error
                 UpdateDataCust.getForUpdate(customer!.custId);
                           },
                           child: Row(mainAxisSize: MainAxisSize.min,
                               children: const <Widget>[
                                           Text('Edit', style: TextStyle(fontSize: 14)),
                                ]
                                 ),
                )
               )
          ),

          ]
        ),
      ),

    );
  }

}


file class CustomerWgtForm.dart
import 'package:flutter/material.dart';
import 'package:sfaf/database/entity/Customer.dart';
import 'package:sfaf/database/impl/CustomerImpl.dart';
import 'package:sfaf/view/screen/master/CustomerScreen.dart';
import 'dart:async';

TextEditingController custCodeController = TextEditingController();
TextEditingController custNameController = TextEditingController();
FocusNode custNameFocusNode = new FocusNode();

bool valueW1 = false;
bool valueW2 = false;
ValueNotifier<bool>  valueNotifierWeek1 = ValueNotifier<bool>(false);
StreamController<bool> streamController = StreamController<bool>();

class CustomerWgtForm extends StatefulWidget {
  @override
  _CustomerWgtFormState createState() => new _CustomerWgtFormState();

 }

class _CustomerWgtFormState extends State<CustomerWgtForm> {
  late FocusNode myFocusNode;
  
  //Call this function in subclass, Erorr
  changedWeek1(bool val) async {
       setState(() {
         valueW1=val;
      });
  }
  changedWeek2(bool val){ setState(() { valueW2=val; }); }

  @override
  void initState() {
      super.initState();
      myFocusNode = FocusNode();
  }
  @override
  void dispose() {
    myFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
       return ListView(
       itemExtent: 700.0,
       shrinkWrap: true,
       scrollDirection: Axis.vertical,
       children: [
         Container(
           child: Stack( 
            alignment: AlignmentDirectional.center,
                     children: <Widget>[
                                 Positioned( top: 10, left: 5, child: 
                                           Text('Cust Code', textAlign: TextAlign.right,) ), 
                                 Positioned( top: 3, left: 90,
                                   child:SizedBox( 
                                     width: 100,height: 35,
                                             child: TextField(
                                                      controller: custCodeController,
                                                      decoration: InputDecoration(
                                                   enabledBorder: OutlineInputBorder(
                                                          borderSide: BorderSide(
                                                                    width: 1, 
                                                                    color: Colors.blueGrey),),
                                                    focusedBorder: OutlineInputBorder(
                                                          borderSide: BorderSide( 
                                                                    width: 1, 
                                                                    color: Colors.amber),),
                                                       ),
                                             ),
                                    )
                                 ),
                                 Positioned( 
                                     top:47, 
                                    left: 5,
                                   child: Text('Cust Name') ),
                                 Positioned( 
                                     top:44,
                                    left: 90,
                                   child:SizedBox(
                       width: 250,height: 35,
                                           child: TextField(
                                controller: custNameController,
                                                    decoration: InputDecoration( 
                                  enabledBorder: OutlineInputBorder(
                                  borderSide: BorderSide(
                                                                      width: 1, 
                                                                      color: Colors.blueGrey),),
                                                          focusedBorder: OutlineInputBorder(
                                                                      borderSide: BorderSide(       
                                                                      width: 1, 
                                                                      color: Colors.amber),),
                                                     ),
                                                     focusNode: custNameFocusNode,
                                          ),
                                  )
                                 ),
                 
                    //WEEK VISITED use Checkbox widget
                    Positioned( 
            top:406, left: 0,
                      child:SizedBox(
                      width: 270,height: 250,
                          child: Padding(
            padding: const EdgeInsets.all(9.0),
                              child: InputDecorator(
                         decoration: InputDecoration(
                          labelText: 'Week Visited', 
                     labelStyle: TextStyle(
                                                  color: Colors.blue),
                                                 border: OutlineInputBorder( 
                                                         borderRadius: BorderRadius.circular(5.0),  
                                                ),
                                                                                                      
                                         contentPadding: EdgeInsets.all(10),
                                     ),
                                     child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                                          children: [
                                              SizedBox(
                           height: 24.0, width: 24.0,
                                                child: Checkbox(
                                                          value: valueW1!,
                                                      onChanged: (bool? val) {
                                                         changedWeek1(val!);
                                                      },
                                                 )
                                               ),
                                               SizedBox(width: 2.0),
                                               Text("W1"),
                                               SizedBox(width: 10.0),
                                               SizedBox(
                        height: 24.0, width: 24.0,
                                                 child: Checkbox( 
                                     value: valueW2,
                                                     onChanged: (bool? val) {
                                                        changedWeek2(val!);
                                                     },
                                                 )
                                               ),
                                               SizedBox(width: 2.0),
                           Text("W2"),
                           SizedBox(width: 10.0),
                                           ]
                                         ),
                                       ),
                                  ),
                         )
                  ),
              ]

  )
  ),
  ],
  );
  }


  }

  //function for reset widget TextField
 clear(){
     custCodeController.text="";
     custNameController.text="";
  }`

  //SUB CLASS
  //Sub class with static function will call in class CustomerWgtLV.dart 
  class UpdateDataCust with ChangeNotifier  {
     static getForUpdate(String? custId) async  {
       try {
             SelectedIndexTabbar.setSelectedIndexTabbarCreateData();

             clear();
             Customer? customer = await CustomerImpl().getCustomerById(custId!.toString());
             custCodeController.text = customer!.custCode.toString();
             custNameController.text = customer!.custName.toString();
             

             CustomerWgtForm m= new CustomerWgtForm();
                  
         //ERROOOOOOR
         //error in this line, while want to set Checkbox with true 
             m.createState().changedWeek1(true);
                  
       }
       catch (e) {
          print(e.toString());
       }
     }

 }

thanks



Aucun commentaire:

Enregistrer un commentaire