Search code examples
fluttersharedpreferencesfuture

Flutter: not being able to show all incoming data


I was using shared_preferences plugin in my Flutter application, I set my data when I click the button, but I try to get my data is not coming.

I set my data here and when I print it, I can see the output on my console.

shows.forEach((element) {
    showCode=element.showName;
    show.setString('showName', showCode);
});

I want to get my data here, above the override method. But when I print here, I just see 1 item, but I need to print 2 items.

  String showCode;

  Future<String> getCode() async{
    final codeValue = await SharedPreferences.getInstance();
    setState((){
      showyCode =codeValue.getString('showName');
    });
    print('here $showCode');
    return showCode;
  }

But I cannot call this future in my function, even if I have 2 data to come but I just see 1 item. I tried to include it in Listview then it fills an entire list with 1 item. Anyone have an idea where I'm doing wrong?

_showProgramData
              ? Container(
            height: MediaQuery.of(context).size.height/2,
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Column(
                    children: [
                      IconButton(icon:Icon(Icons.close) , onPressed:() {Navigator.pushNamed(context, SecondScreen.routeName);}),
                      Text('Please Select Show',style: TextStyle(fontWeight:FontWeight.bold,fontSize: 24),),
                    ],
                  ),
                  Text(showCode),
                ],
              ),
            ),
          ) 

Solution

  • You can copy paste run full code below
    Step 1: You need to use setStringList and getStringList
    Step 2: getCode() return Future<List<String>>
    Step 3: In forEach use showCodeList.add(element.showName);

    code snippet

      void _setData() async {
        shows.forEach((element) {
          showCodeList.add(element.showName);
        });
    
        final codeValue = await SharedPreferences.getInstance();
        await codeValue.setStringList('showName', showCodeList);
    
        setState(() {});
      }
    
      Future<List<String>> getCode() async {
        final codeValue = await SharedPreferences.getInstance();
        showCodeList = await codeValue.getStringList('showName');
        if (showCodeList == null) {
          showCodeList = [];
        }
        print('here ${showCodeList.toString()}');
        return showCodeList;
      }
     ... 
     FutureBuilder(
              future: _future,
              builder: (context, AsyncSnapshot<List<String>> snapshot) {
               ...
                    } else {
                      return ListView.builder(
                          itemCount: snapshot.data.length,
                          itemBuilder: (context, index) {
                            return Card(
                                elevation: 6.0,
                                child: Padding(
                                  padding: const EdgeInsets.only(
                                      top: 6.0, bottom: 6.0, left: 8.0, right: 8.0),
                                  child: Row(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(snapshot.data[index]),  
    

    working demo

    enter image description here

    full code

    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    
    void main() async{
      WidgetsFlutterBinding.ensureInitialized();
      final codeValue = await SharedPreferences.getInstance();
      await codeValue.setStringList('showName', []);
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class Show {
      String showName;
      Show({this.showName});
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      Future<List<String>> _future;
    
      List<Show> shows = [Show(showName: "a"), Show(showName: "b")];
      String showCode;
      List<String> showCodeList = [];
    
      void _setData() async {
        shows.forEach((element) {
          showCodeList.add(element.showName);
        });
    
        final codeValue = await SharedPreferences.getInstance();
        await codeValue.setStringList('showName', showCodeList);
    
        setState(() {});
      }
    
      Future<List<String>> getCode() async {
        final codeValue = await SharedPreferences.getInstance();
        showCodeList = await codeValue.getStringList('showName');
        if (showCodeList == null) {
          showCodeList = [];
        }
        print('here ${showCodeList.toString()}');
        return showCodeList;
      }
    
      @override
      void initState() {
        _future = getCode();
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: FutureBuilder(
              future: _future,
              builder: (context, AsyncSnapshot<List<String>> snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.none:
                    return Text('none');
                  case ConnectionState.waiting:
                    return Center(child: CircularProgressIndicator());
                  case ConnectionState.active:
                    return Text('');
                  case ConnectionState.done:
                    if (snapshot.hasError) {
                      return Text(
                        '${snapshot.error}',
                        style: TextStyle(color: Colors.red),
                      );
                    } else {
                      return ListView.builder(
                          itemCount: snapshot.data.length,
                          itemBuilder: (context, index) {
                            return Card(
                                elevation: 6.0,
                                child: Padding(
                                  padding: const EdgeInsets.only(
                                      top: 6.0, bottom: 6.0, left: 8.0, right: 8.0),
                                  child: Row(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(snapshot.data[index]),
                                    ],
                                  ),
                                ));
                          });
                    }
                }
              }),
          floatingActionButton: FloatingActionButton(
            onPressed: _setData,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
        );
      }
    }