Home > Mobile >  Why the value doesn't change after calling the Setstate() function in flutter
Why the value doesn't change after calling the Setstate() function in flutter

Time:01-29

import 'package:flutter/material.dart';
import 'package:get/get.dart';
//import 'package:get/get_core/src/get_main.dart';
import 'package:intl/intl.dart';
import 'package:menstrual_period_tracker/input2.dart';
import 'package:nepali_date_picker/nepali_date_picker.dart';
class Picker extends StatefulWidget {
const Picker({super.key});
@override
State<Picker> createState() => _PickerState();
}
class _PickerState extends State<Picker> {
NepaliDateTime _dateTime = NepaliDateTime.now();
void _showdatepicker() async {
await showDatePicker(
  context: context,
  initialDate: NepaliDateTime.now(),
  firstDate: NepaliDateTime(2002),
  lastDate: NepaliDateTime.now(),
).then((value) {
  setState(() {
    NepaliDateTime? updatevalue = NepaliDateTime.tryParse(value.toString()),
        _dateTime = updatevalue;
  });
});

} //in my code I have used a nepali date calendar so I have replaced DateTime with NepaliDateTime and the then method uses value which is DateTime so I have to typecast it into the NepaliDateTime and I have assigned that variable to _datetime but the value isn't changing //the warning message is the value of localvaraible isn't used

CodePudding user response:

This is because it is not recommended to perform computation in the setState method.

From the docs:

Generally it is recommended that the setState method only be used to wrap the actual changes to the state, not any computation that might be associated with the change.

In your code sample, you can move the parsing out of the method.

  NepaliDateTime? updatevalue = NepaliDateTime.tryParse(value.toString()),
  setState(() {
    _dateTime = updatevalue;
  });

CodePudding user response:

Maybe error because of comma after toString(). Try to change it to semicolon.

setState(() {
    NepaliDateTime? updatevalue = NepaliDateTime.tryParse(value.toString()); // change to semicolon
    _dateTime = updatevalue;
  });

And also better to move not state changer code from setState:

NepaliDateTime? updatevalue = NepaliDateTime.tryParse(value.toString()); // change to semicolon
setState(() {
  _dateTime = updatevalue;
});
  • Related