简体   繁体   English

为什么在flutter中调用Setstate()后值没有变化 function

[英]Why the value doesn't change after calling the Setstate() function in flutter

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 } //在我的代码中我使用了尼泊尔日期日历所以我用 NepaliDateTime 替换了 DateTime 并且 then 方法使用的值是 DateTime 所以我必须将它转换为 NepaliDateTime 并且我已经将该变量分配给 _datetime 但值是't changing //警告信息是localvaraible的值没有被使用

This is because it is not recommended to perform computation in the setState method.这是因为不建议在setState方法中进行计算。

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.通常建议仅使用 setState 方法来包装对 state 的实际更改,而不是任何可能与更改相关联的计算。

In your code sample, you can move the parsing out of the method.在您的代码示例中,您可以将解析移出方法。

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

Maybe error because of comma after toString().可能由于 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:而且最好不要从 setState 移动 state 转换器代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM