Home > Net >  How to show updated list in shared preferences on UI - Flutter
How to show updated list in shared preferences on UI - Flutter

Time:07-16

I am making an app in a flutter in which I can select the contacts from phone book and saving them in shared preferences. No problem in data saving and retrieving but i m struggling with showing the updated list on my UI. It is showing the contacts list but every time I click on Load button it duplicates the list and showing 2 lists , 1 previous and other updated .

how can i show just updated list on UI ?

here is my code:

import 'package:contacts_test/select_contacts.dart';
import 'package:contacts_test/shared_pref.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'contact_model.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  SharedPref sharedPref = SharedPref();
  ContactModel modelLoad = ContactModel(displayName: 'saniya' , phoneNumber: '324235 ');
  List _list = [];

  @override
  initState() {
    super.initState();
    // Add listeners to this clas
   // loadSharedPrefs();
  }


  loadSharedPrefs() async {
    try {
      print('in load shared pref-- getting keys ');
      final prefs = await SharedPreferences.getInstance();
      final keys = prefs.getKeys();


      print('now load shared pref ');
      for (String key in keys) {
        ContactModel user = ContactModel.fromJson(await sharedPref.read(key));
          _list.add(user);
      }
      print('done load shared pref ');
    }
    catch (Excepetion) {

    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("contacts "),
      ),
      body: Builder(
        builder: (context) {
          return Column(children: [
            RaisedButton(
              onPressed: () {
                Navigator.push(
                    context, MaterialPageRoute(builder: (context) => Plugin1()));
              },
              child: const Text('fluttercontactpicker - plugin1'),

            ),
            RaisedButton(
              onPressed: () async {
                          await loadSharedPrefs();

              },
              child: Text('Load', style: TextStyle(fontSize: 20)),
            ),
            Expanded(
              child: _list.isNotEmpty ?
              ListView.builder(
                shrinkWrap: true,
                itemCount: _list.length,
                itemBuilder: (context, position) {
                  return ListTile(
                      leading: Icon(Icons.contacts),
                      title: Text(

                          _list[position].displayName.toString()
                      ),
                      trailing: Icon(Icons.delete));

                },
              ) : Center(child: Text('No list items to show')),
            ),
          ]);
        }
      ),
    );
  }
}

CodePudding user response:

Your loadSharedPrefs(); function adds each contact to the list you show. Every time you press the button, the same elements are added again to the list. There are multiple ways to avoid that. You can: empty the list before filling it, you can write a for loop to loop over the length of the incoming contacts and for each to add it to the list by always starting from index 0. In case you use some kind of replacement or removing method, make sure you call setState(()=> { });

CodePudding user response:

Base on the answer, here is a possible solution:

import 'package:contacts_test/select_contacts.dart';
import 'package:contacts_test/shared_pref.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'contact_model.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  SharedPref sharedPref = SharedPref();
  ContactModel modelLoad = ContactModel(displayName: 'saniya' , phoneNumber: '324235 ');
  List _list = [];

  @override
  initState() {
    super.initState();
    // Add listeners to this clas
   // loadSharedPrefs();
  }


  loadSharedPrefs() async {
    try {
      print('in load shared pref-- getting keys ');
      final prefs = await SharedPreferences.getInstance();
      final keys = prefs.getKeys();


      print('now load shared pref ');
      var newList = [];

      for (String key in keys) {
        ContactModel user = ContactModel.fromJson(await sharedPref.read(key));
          newList.add(user);
      }
      setState(()=> { _list = newList; });
      print('done load shared pref ');
    }
    catch (Excepetion) {

    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("contacts "),
      ),
      body: Builder(
        builder: (context) {
          return Column(children: [
            RaisedButton(
              onPressed: () {
                Navigator.push(
                    context, MaterialPageRoute(builder: (context) => Plugin1()));
              },
              child: const Text('fluttercontactpicker - plugin1'),

            ),
            RaisedButton(
              onPressed: () async {
                          await loadSharedPrefs();

              },
              child: Text('Load', style: TextStyle(fontSize: 20)),
            ),
            Expanded(
              child: _list.isNotEmpty ?
              ListView.builder(
                shrinkWrap: true,
                itemCount: _list.length,
                itemBuilder: (context, position) {
                  return ListTile(
                      leading: Icon(Icons.contacts),
                      title: Text(

                          _list[position].displayName.toString()
                      ),
                      trailing: Icon(Icons.delete));

                },
              ) : Center(child: Text('No list items to show')),
            ),
          ]);
        }
      ),
    );
  }
}
  • Related