Evripides Kyriacou
Evripides Kyriacou

Reputation: 85

Flutter List Sometime is empty

i have the below code that I am receiving from API a list with posts , when I open the application the list if I saved to code again the list display correctly , but every time that i restart the app the list is empty, any ideas? I am new in flutter so if I have something stupid please forgive me

I am using VS and I am running the app via VS debugger, also I dont get any error, maybe the list is not available?

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter1/screen/login.dart';
import 'package:flutter1/network_utils/api.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:developer' as developer;

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home>{
  //final List<String> people = ['george','evripides','vicky'];
 // var posts;
List<dynamic> posts = [];


  String name;
  @override
  void initState(){
    _loadUserData();
    _loadPosts();
    super.initState();
  }

  _loadUserData() async{
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    var user = jsonDecode(localStorage.getString('user'));
    //developer.log(user);
    if(user != null) {
      setState(() {
        name = user;
      });
    }
  }

  Future _loadPosts() async{
   await Network().getDataPosts('post/getallposts?page=1').then((res) {
    developer.log("home"+ res.body);
    var posts1 = jsonDecode(res.body);
    print(posts1);
    posts = posts1['data']['data'];
    print(posts[1]['title']);
    print(posts.length);
    return posts.toList();
   },
   onError: (error) {
    print(error);
   });
    //var res = await Network().getDataPosts('post/getallposts?page=1');
  }


    @override
    Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Test App'),
            backgroundColor: Colors.teal,
          ),
          body: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text('Hi, $name',
                  style: TextStyle(
                    fontWeight: FontWeight.bold
                    ),
                  ),
              new Expanded(
                child: posts.isEmpty ? Center(child: Text('Empty')) : ListView.builder(
                  itemCount: posts.length,
                  itemBuilder: (context, index) {
                    var item = posts[index]['title'];
                    var item2 = posts[index]['comments'];
                    var item3 = posts[index]['country'];
                    return Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
                      child: Card(
                        elevation: 10.0,
                        child: ListTile(
                          title: Text('$item  ${item3 == 'Cyprus' ? true : item3}'),
                          subtitle: Text(item2),
                          trailing: GestureDetector(
                              child: Icon(
                                Icons.dehaze,
                                color: Colors.black,
                              ),
                              onTap: () {
                                setState(() {
                                  posts.remove(item);
                                });
                              }),
                        ),
                      ),
                    );
                  }),
                  ),

                  Center(
                    child: RaisedButton(
                      elevation: 10,
                      onPressed: (){
                        logout();
                      },
                      color: Colors.teal,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
                      child: Text('Logout'),
                    ),
                  ),
                ],
              ),
          ),
        );
      }



  void logout() async{
 //   var res = await Network().getData('/logout');
   // var body = json.decode(res.body);
    //if(body['success']){
      SharedPreferences localStorage = await SharedPreferences.getInstance();
      localStorage.remove('user');
      localStorage.remove('token');
      Navigator.push(
          context,
          MaterialPageRoute(builder: (context)=>Login()));

  }
}

Upvotes: 0

Views: 1066

Answers (1)

Viren V Varasadiya
Viren V Varasadiya

Reputation: 27137

As getting data from server is async task s it takes time to complete, so when you get data you have to call setState and you are not calling setstate and because of that you are facing this behaviour.

setState((){
   posts = posts1['data']['data'];
});   

Upvotes: 1

Related Questions