Home > OS >  the value doesn't get assigned when i pass the sharedpreference data into it, i am able to prin
the value doesn't get assigned when i pass the sharedpreference data into it, i am able to prin

Time:11-13

what im trying to do is passing a value hour into another page, into the dropdownbar for user to update the hour, but when i tried to use sharedpreference to store the data and get the data out. I am able to print out the data during the print(get) but the dropdownvalue which assigned the get value, it is empty and get assigned the initial value which is 1.

class UpdateService extends StatefulWidget {
  final String serviceName;
  final String serviceDetails;
  final String serviceImage;

  UpdateService({required this.serviceName, required this.serviceDetails,
  required this.serviceImage});

  @override
  State<UpdateService> createState() => UpdateServiceState();
}
String dropdownvalue = '1';
class UpdateServiceState extends State<UpdateService> {
  TextEditingController serviceDetailsController = TextEditingController();
  TextEditingController hoursNeedController = TextEditingController();

  var items = ['1', '2', '3', '4',
    '5', '6', '7', '8', '9'];

  @override
  void initState(){
    serviceDetailsController = TextEditingController(text: widget.serviceDetails.toString());
    loadPref();
    super.initState();
  }

  loadPref() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //Return String
    String get = prefs.getString('hour').toString() ?? "none";
    dropdownvalue = get;
    print(get);
  }

  Widget build(BuildContext context) {

DropdownButton(
                  value: dropdownvalue,
                  items: items.map((String items){
                    return DropdownMenuItem(
                        value: items,
                        child: Text(items));
                  }).toList(),
                  onChanged: (String? newValue){
                    setState(() {
                      dropdownvalue = newValue!;
                    });
                  }),

well i run out of ideas on how to pass it, i hope someone can help me

CodePudding user response:

String get = prefs.getString('hour').toString();

will try to get it if it's stored, but you don't have it saved yet so it throw null and you can't assign null to a non nullable Object which is String in your case, so you need to make it nullable and give it a default value when it's null, so:

replace:

    String get = prefs.getString('hour').toString();

with this:

    String? get = prefs.getString('hour').toString() ?? "default value here";
  • Related