Shared preferences remove data on app close, no debug

All owrks prefect on debug but when i compile all works perfect til i close the app and opened again it deletes previus data, heres my code.

//Flutter version v1.9.1+hotfix.6
import 'package:flutter/material.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';

void main() => runApp(Master());

class Master extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'QrBar Scanner',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MasterFul(title: 'QrBar Scanner'),
    );
  }
}

class MasterFul extends StatefulWidget {
  MasterFul({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MasterFulState createState() => _MasterFulState();
}

// class _MasterFulState extends State<MasterFul> {

//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       backgroundColor: Colors.blueGrey[800],
//       appBar: AppBar(
//         title: Text(widget.title),
//       ),
//       body: Center(
//         child: Column(
//           mainAxisAlignment: MainAxisAlignment.center,
//           children: <Widget>[
//             Text(
//               'Scan Results',
//               style: TextStyle(
//                   fontWeight: FontWeight.bold,
//                   fontSize: 20,
//                   color: Colors.white),
//             ),
//             new FlatButton(
//               onPressed: _launchURL,
//               child: new Text(_value,
//                   style: TextStyle(
//                       fontWeight: FontWeight.bold,
//                       fontSize: 20,
//                       color: Colors.yellowAccent)),
//             ),
//             Container(
//                 child: Image.asset('assets/images/saturnavt.png', width: 46, height: 46),
//             ),
//             Container(

//               child: Text("Saturnavt",
//               style: TextStyle(color: Colors.white),
//               )
//             ),
//             Container(
//               height: 200,
//               child: TabBarDemo()
//             ),
//           ],
//         ),
//       ),
//       floatingActionButton: FloatingActionButton(
//         onPressed: _scan,
//         tooltip: 'Scan',
//         child: Icon(Icons.settings_overscan),
//       ),
//     );
//   }
// }

//Tabs
class _MasterFulState extends State<MasterFul> {
  static String _scanner, _value = "https://flutter.dev";
  static String data = "";

  @override
  void initState() {
    super.initState();
    const MethodChannel("plugins.flutter.io/shared_preferences")
        .setMockMethodCallHandler(
      (MethodCall methodcall) async {
        if (methodcall.method == "getAll") {
          return {"flutter." + 'history': "[ No Name Saved]"};
        }
        return null;
      },
    );
    setData();
  }

  Future<bool> saveData() async {
    // Async func to handle Futures easier; or use Future.then
    SharedPreferences prefs = await SharedPreferences.getInstance();
    // Set
    return await prefs.setString('history', _value);
  }

  Future<String> loadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    // Get
    return prefs.getString('history');
  }

  setData() {
    loadData().then((value) {
      setState(() {
        data = value;
      });
    });
  }

  Future _scan() async {
    _scanner =
        await FlutterBarcodeScanner.scanBarcode("#ff6666", "Cancel", true);
    setState(() {
      _value = _scanner;
    });
    await saveData();
    setData();

    await loadData();
  }

  _launchURL() async {
    String url = _scanner;
    if (isNumeric(url) == true) {
      if (await canLaunch("https://flutter.dev")) {
        //await launch("https://flutter.dev");
      } else {
        throw 'Could not launch $url';
      }
    } else {
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        //throw 'Could not launch $url';
      }
    }
  }

  bool isNumeric(String s) {
    if (s == null) {
      return false;
    }
    return double.tryParse(s) != null;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 2,
        child: Scaffold(
          backgroundColor: Colors.blueGrey[800],
          appBar: AppBar(
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.settings_overscan)),
                Tab(icon: Icon(Icons.av_timer)),
              ],
            ),
            title: Text('Qr Bar Scanner'),
          ),
          body: TabBarView(
            children: [
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    'Scan Results',
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 20,
                        color: Colors.white),
                  ),
                  new FlatButton(
                    onPressed: _launchURL,
                    child: new Text(_value,
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                            color: Colors.yellowAccent)),
                  ),
                  // Container(
                  //   child: Image.asset('assets/images/saturnavt.png',
                  //       width: 46, height: 46),
                  // ),
                  // Container(
                  //     child: Text(
                  //   "Saturnavt",
                  //   style: TextStyle(color: Colors.white),
                  // )),
                ],
              ),

              
              Container(
                height: 50,
                
               
                  child: Column(
                    
                    children: <Widget>[
                      
                      ListTile(
                        leading: Icon(Icons.album),
                        title: Text(data),
                      ),
                      ButtonBar(
                        children: <Widget>[
                          FlatButton(
                            child: const Text("Share"),
                            onPressed: () {/* ... */},
                          ),
                          FlatButton(
                            child: const Text("Open"),
                            onPressed: () {/* ... */},
                          ),
                        ],
                      ),
                    ],
                  ),
              )
            ],
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _scan,
            tooltip: 'Scan',
            child: Icon(Icons.settings_overscan),
          ),
        ),
      ),
    );
  }
}

I haven’t used shared preference much to be able to understand it completely.

This is what I could think of.
When the app is launched second time onwards, maybe it is overwriting the previous data instead of appending.

1 Like

Hello i was using bad the async await but i fixed thanks a lot.

1 Like