Home > Software design >  How to access a variable from another dart file . Flutter
How to access a variable from another dart file . Flutter

Time:02-09

I am new to Flutter and I need to access a variable from another dart file.I am using showDatePicker to select a date.I need to get that date in another file in which where dob.dart is calling to insert in database.

dob.dart

class _DateOfBirthState extends State<DateOfBirth> {
  DateTime? dateTime;
  String _text = '';
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(),
        borderRadius: BorderRadius.circular(5),
      ),
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('Date Of Birth'),
            Text(_text),
            ElevatedButton(
              onPressed: () async {
                dateTime = await showDatePicker(
                  context: context,
                  initialDate: dateTime ?? DateTime.now(),
                  firstDate: DateTime(1900),
                  lastDate: DateTime.now(),
                );
                setState(() {
                  _text =
                      '${dateTime?.day}/${dateTime?.month}/${dateTime?.year}';
                });
              },
              child: const Text('Date Of Birth'),
            ),
          ],
        ),
      ),
    );
  }
}

I need to use value of dateTime in another file addStudents.dart

addstudents.dart

class _AddStudentsState extends State<AddStudents> {
  final _nameController = TextEditingController();
  final _addressController = TextEditingController();
  final _mobileController = TextEditingController();
  final _emailController = TextEditingController();
  final GlobalKey<FormState> _formkey = GlobalKey<FormState>(); @override
  Widget build(BuildContext context) {
    return Center(
      child: SingleChildScrollView(
        child: Form(
          key: _formkey,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              children: [
                TextFormField(
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Enter your name';
                    }
                  },
                  controller: _nameController,
                  decoration: const InputDecoration(
                      labelText: 'Name',
                      hintText: 'Alex',
                      border: OutlineInputBorder()),
                ),                
                DateOfBirth(),               
                TextFormField(
                  maxLines: 5,
                  keyboardType: TextInputType.multiline,
                  controller: _addressController,
                  decoration: const InputDecoration(
                      labelText: 'Address',
                      hintText:
                          'House 21\nKolachery mukk\nP.O.Kolachery\nKannur\n670601',
                      border: OutlineInputBorder()),
                ),               
                TextFormField(
                  maxLength: 10,
                  keyboardType: TextInputType.number,
                  controller: _mobileController,
                  decoration: const InputDecoration(
                    labelText: 'Mobile Number',
                    prefixText: ' 91',
                    hintText: '0000000000',
                    border: OutlineInputBorder(),
                  ),
                ),                
                TextFormField(
                  keyboardType: TextInputType.emailAddress,
                  controller: _emailController,
                  decoration: const InputDecoration(
                      labelText: 'Email',
                      hintText: '[email protected]',
                      border: OutlineInputBorder()),
                ),         
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    child: const Text('Submit'),
                    onPressed: () async {
                      if (!_formkey.currentState!.validate()) {
                        return;
                      }

                      await DataBaseHelper.instance.addStudent(
                        StudentDetails(
                          name: _nameController.text,
                          dob:
                              // '${dateTime!.day}/${dateTime!.month}/${dateTime!.year}',
                          address: _addressController.text,
                          phone: _mobileController.text,
                          email: _emailController.text,
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

If you are navigating from dob.dart to addstudents.dart then you can pass the value of DateTime though the constructor.

or

you can store it inside local database like sharedpreferences, and access it in any file.

CodePudding user response:

You need to import the file with the variable dateTime.

Then you have to ways:

  1. make the variable static: static var dateTime
  2. for this way you don't need todo know anything

so if you have make the variable static you can use it also in a other file if you import the file with the static varible and you use it like this: ClassWithTheStaticVarible.dateTime.

and if you do way number 2 than you need to import the file with the variable and you can use it like this: ClassWithTheDateTimeVarible().dateTime

so what it does if you use way 1: it pick the varible out of the class without build the class again.

and if you use way 2 it does: build the class again and pick after this the variable

  •  Tags:  
  • Related