如何将选择的值存储在字符串中,以便在重新启动应用程序后显示最后选择的值?

我正在设置Flutter本地通知,一切进展顺利,但是我想将所选值存储在文本中,因此,如果应用重新启动,它将显示所选值,而不是重置为默认值。 例如,如果我在08:08:08选择通知,那么在选择通知并重新启动应用程序后,无论何时我进入通知选择时间,它都应显示08:08:08(最后选择的值)。

我尝试过setstate(){}; 但值始终在重启应用后重置。 这是我的代码。

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';
class SettingPage extends StatefulWidget {
  @override
  _SettingPage createState() => _SettingPage();
}

  class _SettingPage extends State<SettingPage> {
  ///Flutter Local Notification
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  String notifyTime ="your time";
  String nhour ="";
  String nminutes ="";
  String nseconds ="";


    @override
    initState() {
    super.initState();
    // initialise the plugin. app_icon needs to be a added as a drawable 
    resource to the Android head project
    // If you have skipped STEP 3 then change app_icon to @mipmap/ic_launcher
    var initializationSettingsAndroid =
    new AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettingsIOS = new IOSInitializationSettings();
    var initializationSettings = new InitializationSettings(
        initializationSettingsAndroid,initializationSettingsIOS);

    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    flutterLocalNotificationsPlugin.initialize(initializationSettings);
    }
    Future _showNotificationWithDefaultsound() async {
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
        'your channel id','your channel name','your channel description',importance: Importance.Max,priority: Priority.High);
    var iOSPlatformChannelSpecifics = new IOsnotificationDetails();
    var platformChannelSpecifics = new NotificationDetails(
        androidPlatformChannelSpecifics,iOSPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
      0,'Learn Local Notification','A Local Notification On Button Click',platformChannelSpecifics,payload: 'Default_Sound',);
  }

  Future scheuleAtParticularTime(DateTime timee) async {
    var time = Time(timee.hour,timee.minute,timee.second);

    print(time.toString());
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
        'repeatDailyAtTime channel id','repeatDailyAtTime channel name','repeatDailyAtTime description');
    var iOSPlatformChannelSpecifics = new IOsnotificationDetails();
    var platformChannelSpecifics = new NotificationDetails(
        androidPlatformChannelSpecifics,iOSPlatformChannelSpecifics);
    flutterLocalNotificationsPlugin.showDailyAtTime(0,'Hey! Check your 
    today`s horoscope ','Login now to see your today`s horoscope !',time,platformChannelSpecifics);
    print('scheduled');
    Fluttertoast.showToast(
        msg:
        "Notification Scheduled for ${time.hour} : ${time.minute} : 
    ${time.second}",toastLength: Toast.LENGTH_SHORT,gravity: ToastGravity.BOTTOM,// also possible "TOP" and "CENTER"
        backgroundColor: Colors.grey,textColor: Colors.white);
    setState(() {
      nhour = time.hour.toString();
      nminutes=time.minute.toString();
      nseconds=time.second.toString();
      notifyTime=nhour+" : "+nminutes+" : "+nseconds;

    });
  }
  //function ends
 @override
  Widget build(BuildContext context) {
    return Scaffold(backgroundColor: Theme.of(context).primaryColor,appBar: AppBar(backgroundColor: Theme.of(context).primaryColor,leading: IconButton(icon: Icon(FontAwesomeIcons.arrowLeft,//backgroundColor: Theme.of(context).primaryColor,),onpressed: () => {
          Navigator.pop(context),}),title: Text('Setting'),body: Theme( data: Theme.of(context).copyWith(
        canvasColor: Theme.of(context).primaryColor,//This will change the drawer background to blue.),child: Center(
          child: Container(
            height: MediaQuery
                .of(context)
                .size
                .height - 60.0,child: ListView(
              scrollDirection: Axis.horizontal,children: <Widget>[
                Padding(
 padding: const EdgeInsets.only(top: 60.0),child: RaisedButton(
                                  color:  Color(0xffffffff),child: Text('Notification time - $notifyTime',////NEED TO STORE LAST VALUE HERE////////
                                    style: TextStyle(
                                      color:  Color(0xff6200ee),onpressed: () {
                                    DatePicker.showTimePicker(context,showTitleactions: true,onChanged: (date) {
                                          print('change $date');
                                        },onconfirm: (date) {
                                          print('confirm $date');
                                          scheuleAtParticularTime(
                                              DateTime.fromMillisecondsSinceEpoch(
                                                  date.millisecondsSinceEpoch));
                                        },currentTime: DateTime.now(),locale: LocaleType.en);
                                  },shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(
                                        30.0),)
                              ),],);
}
}
haosansan 回答:如何将选择的值存储在字符串中,以便在重新启动应用程序后显示最后选择的值?

即使重新启动,您也可以使用shared_preferences插件将数据存储在设备上并在应用程序中使用。

首先导入共享的首选项插件:

import 'package:shared_preferences/shared_preferences.dart';

要存储数据,只需执行以下操作:

SharedPreferences prefs = await SharedPreferences.getInstance();
bool storedSuccessfully = await prefs.setString('<Your_Key>',<Your_String_Value>);

要获取存储的数据:

SharedPreferences prefs = await SharedPreferences.getInstance();
String storedValue = prefs.getString('<YOUR-KEY>');

因此,在您的情况下,每次用户选择该值时,您只需要将其与键一起存储,然后在每次应用程序重新启动时,只需使用您提供的键来获取该值,然后使用它即可。 / p>

本文链接:https://www.f2er.com/3132327.html

大家都在问