Home > Net >  not getting list of user when I use api in initstate in flutter
not getting list of user when I use api in initstate in flutter

Time:11-01

I am trying to fetch user from an api within the initState method, but It does not show user list. Looks like failing to rebuild screen

it worked when I place a elevated button and on its press it fetch data from api..but here I don't want to place any button..it should be shown on loading app

here is my code

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();


}

class _HomeScreenState extends State<HomeScreen> {
  List<dynamic> userlist = [];
  bool isloading = false;
  
  void fetchdata() async
  {
    setState(() {
      isloading = true;
    });
    //var res = await http.get(Uri.https("dummyjson.com", "users"));

    var res = await http.get(
        Uri.parse('https://jsonplaceholder.typicode.com/posts'));

    if (res.statusCode == 200) {
      var jsondata = jsonDecode(res.body);
      print(jsondata);
      print(jsondata['users']);
      setState(() {
        userlist = jsondata;
        isloading = false;
      });
    }
  }


  @override
  void initState()  {
    // TODO: implement initState
    super.initState();
    fetchdata();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
      body: MyBody(),
    ));
  }

  MyBody() {
    return userlist.isNotEmpty
        ? Column(
            children: [
              Text('List Of Users'),
              SizedBox(
                height: 20,
              ),
              Expanded(
                child: ShowUser(userlist:userlist),
              )
            ],
          )
        : Center(
            child: Text('No user found'),
          );
  }


  }

CodePudding user response:

remove this line print(jsondata['users']);

 if (res.statusCode == 200) {
      var jsondata = jsonDecode(res.body);
      print(jsondata);
     // print(jsondata['users']); <= remove this line. this is caused error..
      setState(() {
        userlist = jsondata;
        isloading = false;
      });

for better programming style. while fetch api, i recommend to use try{} catch{}. it will help you to handle if there's any error. with your current code, the error occurs while printing null doesnt exist value. but you are not catch any error. so you dont know what is going wrong.

try{
  var res = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
 .... here another code

} catch  (e){
   print(e); // here you can handle the error
}
  • Related