Home > Net >  How to resolve "A value of type 'String?' can't be assigned to a variable of typ
How to resolve "A value of type 'String?' can't be assigned to a variable of typ

Time:11-01

I tried to calculate age from datepicker but into that datepicker I added sharedpreference.And to calculate age I got "dropdownValueBirthday" equal to " birthday" .Then display null . How I fix this error? But birthday display nicely I want calculate age from birthday and should display age as duration.

image

enter image description here

duration is still null

code

  void initState() {
    super.initState();
    dropdownValueBirthday = birthday.first;
    checkValueBirthday();

  }


  //age
 
  String age = "";
  DateDuration? duration;
  //date picker
  //date picker
  DateTime? selectedDate;
  DateTime now = new DateTime.now();
  void showDatePicker() {
    DateTime mindate = DateTime(now.year - 2, now.month, now.day - 29);
    DateTime maxdate = DateTime(now.year - 1, now.month, now.day);
    showCupertinoModalPopup(
        context: context,
        builder: (BuildContext builder) {
          return Container(
            height: MediaQuery.of(context).copyWith().size.height * 0.25,
            color: Colors.white,
            child: CupertinoDatePicker(
              mode: CupertinoDatePickerMode.date,
              initialDateTime: mindate,
              onDateTimeChanged: (valueBirth) {
                if (valueBirth != selectedDate) {
                  setState(() {
                    selectedDate = valueBirth;
                    dropdownValueBirthday =
                        '${selectedDate?.year}/${selectedDate?.month}/${selectedDate?.day} ';
                    calAge();
                  });
                }
              },
              maximumDate: maxdate,
              minimumDate: mindate,
            ),
          );
        });
  }

  void calAge() {
    DateTime birthday = DateTime.parse(dropdownValueBirthday!);

    setState(() {
      duration = AgeCalculator.age(birthday);
    });
    // print('Your age is $duration');
  }

  String? dropdownValueBirthday;
  List<String> birthday = [
    'Birthday',
  ];

  checkValueBirthday() {
    _getDataBirthday();
  }

  _saveDataBirthday(String dropdownValueBirthdayShared) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString("dataBirthday", dropdownValueBirthdayShared);
  }

  _getDataBirthday() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    dropdownValueBirthday =
        sharedPreferences.getString("dataBirthday") ?? birthday.first;
    setState(() {});
  }

widget code

 child: GestureDetector(
                          onTap: (showDatePicker),
                          child: SizedBox(
                            width: 110.0,
                            height: 25.0,
                            child: DecoratedBox(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(12),
                                color: Colors.white,
                              ),
                              child: Center(
                                child: Text(
                                  selectedDate == null
                                      ? (dropdownValueBirthday ??
                                          birthday.first)
                                      : '${selectedDate?.year}/${selectedDate?.month}/${selectedDate?.day} ',
                                  style: const TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w500),
                                ),
                              ),
                            ),
                          ),
                        ),

print enter image description here

new error enter image description here

CodePudding user response:

you need to convert string to DateTime

DateTime? birthday = DateTime.parse(dropdownValueBirthday);

CodePudding user response:

To convert a String into a DateTime, you cannot use as. as can be used if the actual type of the object is a child type of it. You can check the type with is. For instance:

void main() {

  ParentClass actualParent = ParentClass();
  ParentClass hiddenChild = ChildClass();
  ChildClass actualChild = ChildClass();
  
  print(actualParent is ChildClass); // false
  print(hiddenChild is ChildClass); // true
  print(actualChild is ChildClass); // true
}

class ParentClass {
  String getType() => 'parent';
}

class ChildClass extends ParentClass {
    @override
    String getType() => 'child';
}

If you want to convert a String into a DateTime, you have to use DateTime.tryParse(String). See the official docs for more information on DateTime.

EDIT

To calculate the age by a birthday, you need the duration between that day and today (or any other day).

void main() {
  DateTime birthday = DateTime.parse("1970-01-01");
  DateTime today = DateTime.now();
  
  Duration age = today.difference(birthday);
  print('${age.inDays} days'); // 19297 days (at 2022-11-01)
}

CodePudding user response:

Try the following code:

  void initState() {
    super.initState();
    dropdownValueBirthday = birthday.first;
    checkValueBirthday();

  }


  //show date picker
//age
  //Radio button variable declare
  String age = "";
  DateDuration? duration;
  //date picker
  //date picker
  DateTime? selectedDate;
  DateTime now = new DateTime.now();
  void showDatePicker() {
    DateTime mindate = DateTime(now.year - 2, now.month, now.day - 29);
    DateTime maxdate = DateTime(now.year - 1, now.month, now.day);
    showCupertinoModalPopup(
        context: context,
        builder: (BuildContext builder) {
          return Container(
            height: MediaQuery.of(context).copyWith().size.height * 0.25,
            color: Colors.white,
            child: CupertinoDatePicker(
              mode: CupertinoDatePickerMode.date,
              initialDateTime: mindate,
              onDateTimeChanged: (valueBirth) {
                if (valueBirth != selectedDate) {
                  setState(() {
                    selectedDate = valueBirth;
                    dropdownValueBirthday =
                        '${selectedDate?.year}/${selectedDate?.month}/${selectedDate?.day} ';
                  });
                }
              },
              maximumDate: maxdate,
              minimumDate: mindate,
            ),
          );
        });
  }

  void calAge() {
    DateTime birthday = DateTime.parse(dropdownValueBirthday);

    setState(() {
      duration = AgeCalculator.age(birthday);
    });
    // print('Your age is $duration');
  }

  String? dropdownValueBirthday;
  List<String> birthday = [
    'Birthday',
  ];

  checkValueBirthday() {
    _getDataBirthday();
  }

  _saveDataBirthday(String dropdownValueBirthdayShared) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString("dataBirthday", dropdownValueBirthdayShared);
  }

  _getDataBirthday() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    dropdownValueBirthday =
        sharedPreferences.getString("dataBirthday") ?? birthday.first;
    setState(() {});
  }
  • Related