Search code examples
flutterdartflutter-layout

Appbar should show number of records using futurebuilder in flutter


I have just created a demo for better understanding future builder

scaffold body showing all users from api and appear should be shown with number of users

appear's title showing 0 when loaded but does not change...what to do to rebuild it

here is my code


class _withmodelState extends State<withmodel> {

  List<UserModel> userlist=[];

  Future<List<UserModel>> getdata() async {
    final resp =
        await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));

    if (resp.statusCode == 200) {
      print('i ma called');
      List<dynamic> dlist = json.decode(resp.body);
      await Future.delayed(Duration(seconds: 2));

      userlist= dlist.map((e) => UserModel.fromJson(e)).toList();
      return userlist;
    }
    return userlist;


  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
          appBar: AppBar(title: Text("Total users="+userlist.length.toString()),),
      body: MyBody(
        //MyBody returning FutureBuilder for showing userlist array;
      ),
    ));
  }

Solution

  • You can use ChangeNotifier like this, first create a class like this:

    class WithmodelDecl with ChangeNotifier {
      ValueNotifier<int> totalUsers = ValueNotifier<int>(0);
    }
    
    WithmodelDecl withmodeldecl = new WithmodelDecl();
    

    then use it like this:

    return SafeArea(
            child: Scaffold(
              appBar: PreferredSize(
              child: ValueListenableBuilder<int>(
                  valueListenable: withmodeldecl.totalUsers,
                  builder: (context, value, _) {
                    return AppBar(
                      title: Text("Total users=" + value.toString()),
                    );
                  }),
              preferredSize: AppBar().preferredSize),
          body: MyBody(
            //MyBody returning FutureBuilder for showing userlist array;
          ),
    ));
    

    and finally change your getdata to this:

    Future<List<UserModel>> getdata() async {
        final resp =
            await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
    
        if (resp.statusCode == 200) {
          print('i ma called');
          List<dynamic> dlist = json.decode(resp.body);
          await Future.delayed(Duration(seconds: 2));
    
          userlist= dlist.map((e) => UserModel.fromJson(e)).toList();
          withmodeldecl.totalUsers.value = userlist.length;
          return userlist;
        }
        return userlist;
    
    
      }