How to store selected value in a string so that after restart app it shows last selected value?

0

I'm setting up flutter local notification, all is going well but i want to store the selected value in a text so if the app restart it will show selected value rather then resetting to default. For example if I choose notification at 08:08:08 so after selecting it and restarting app whenever i go to notification selection time it should show 08:08:08(last selected value).

i have tried setstate(){}; but value always reset after restarting app. here is my code.

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),)
                              ),
                            ),
 ],),


                ),
);
}
}
flutter
notifications
flutter-dependencies
asked on Stack Overflow Nov 9, 2019 by shivam

1 Answer

0

you can use the shared_preferences plugin to store data on the device and use it in the app, even after it restarts.

First import the shared preferences plugin:

import 'package:shared_preferences/shared_preferences.dart';

To store data, simply do:

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

To get the stored data:

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

So in your case, every time a user selects the value, you just have to store it with a key, and then every time the app restarts, simply fetch that value using the key you gave it, and use it.

answered on Stack Overflow Nov 9, 2019 by Ayush Shekhar

User contributions licensed under CC BY-SA 3.0