Home > Back-end >  if I set internet off circularprogress indication does not stop
if I set internet off circularprogress indication does not stop

Time:09-07

I am beginner and creating a demo for json data,

here what should I implement my code, so that circularprogressindicator should be gone on if I switch off internet...

I know this is a very basic question but being honest I am totally failing to understand future, so I can't solve this issue...I am trying to understand with examples...

class _UserScreenState extends State<UserScreen> {

  List<User>? userlist;
  bool isloading=true;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
      ApiServices.getusers().then((value) {
     setState(() {
       userlist=value;
       isloading=false;
     });
   });
    
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:  isloading==true?Center(child: CircularProgressIndicator()):ListView.builder(
          itemCount: userlist==null?0:userlist!.length,
          itemBuilder: (context,index){
            User user=userlist![index];
            return ListTile(
              title: Text(user.name.toString()),
              subtitle: Text(user.email.toString()),
              leading: CircleAvatar(child: Text(user.id.toString()),),

            );
          }),


    );
  }
}

here is my Api class

class ApiServices
{

  static const String url='https://jsonplaceholder.typicode.com/users';

  static Future<List<User>> getusers() async{

    List<User> userlist=[];
    try
    {
      final response=await http.get(Uri.parse(url));

      if(response.statusCode==200)
      {
        final jsondata=json.decode(response.body);
        userlist.clear();
        for(var data in jsondata)
        {
          userlist.add(User.fromJson(data));
        }
      }
      return userlist;
    }catch(e)
    {
      return userlist;
    }
    return userlist;

  }

}


CodePudding user response:

you initialize the isLoading = true . thats why, default widget in your body is circularprogressIndicator

you have to set false first.

 bool isloading=false; // so the circular only show when fetching data
  @override
  void initState() {
    setState((){ isloading= true;});  // show the loading
      ApiServices.getusers().then((value) {
     setState(() {
       userlist=value;
       isloading=false; // false when its complete, 
     });
   });
  super.initState();
    
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
..............

also you can add another condition, when Api failed, then response user is null

you can show something like

userlist.length< 1 ? Text("Data not found") : ....your list tile

CodePudding user response:

Use timeout to stop in the case of poor or no connection.

final response = await http.get(Uri.parse(url)).timeout(const Duration(seconds: 15));
  • Related