简体   繁体   中英

How to change FutureBuilder connection.state in flutter

Here i am hitting an api to get the data but and i am getting the data as i have printed the data. But when i am using FutureBuilder connection.state it is returning none and returns the view. I want to know how to change the state of connection.state to Done so that i can show my view.

*class DashboardScreen extends StatefulWidget {
  @override
  _DashboardScreen createState() => _DashboardScreen();
}
class _DashboardScreen extends State<DashboardScreen> {
Future<DashboardModel> futureDashboard;
//   api hit

@override
      void didChangeDependencies() {
        super.didChangeDependencies();
        Future.delayed(Duration.zero, () {
          WidgetsBinding.instance.addPostFrameCallback((_) async{
            
            futureDashboard = dashboardData();
          }
          );
        });
      }

// here is dashboard data

Future<dynamic> dashboardData() async {
    pr.show();
    final String url =
        '${GlobalConfiguration().getString('api_base_url')}${GlobalConfiguration().getString('dashboard')}';

    final response = await http.post(
      url,
      body: {
        "auth_key": '${GlobalConfiguration().getString('auth_key')}',
      },
    );

    responseJson = json.decode(response.body);
    Map<String, dynamic> map = jsonDecode(response.body);
    DashboardModel dashboardModel = DashboardModel.fromJson(map);
    _dashboard = DashboardModel.fromJson(responseJson);
    if (_dashboard.statusCode == "200") {

      final String responseString = response.body;


      pr.hide();
      showSimpleFlushbar(context, 'Successful');
      return dashboardModelFromJson(responseString);
    } else {

      pr.hide();
      return null;
    }
  }



// setting the data in the view created
 @override
  Widget build(BuildContext context) {

// scaffold view
    return new Scaffold(
      
      body: Container(
        height: double.infinity,
        width: double.infinity,
    
padding: EdgeInsets.symmetric(vertical: 10),
    child: FutureBuilder<DashboardModel>(
        future: futureDashboard,
        builder: (context, AsyncSnapshot<DashboardModel> futureDashboard) {
          switch (futureDashboard.connectionState) {
            case ConnectionState.none:
              return Container(
                  child: Center(
                      child: Text(
                          'No Connection Message')
                  )
              );
            case ConnectionState.active:
              return Text('Active result...');
            case ConnectionState.waiting:
              return Text('Awaiting result...');
            case ConnectionState.done:
              print(futureDashboard);
              if (futureDashboard.hasData) {
                  ListTile(
                    title: Text("data"),);
                    } else if (futureDashboard.hasError) {
                  return showSimpleFlushbar(context, "${futureDashboard.error}");
                }
                return Container(
                  child: Text('error'),
                );
              }
              return Container(
                child: Text('errornot'),
              );
          }),
  ),
);
}*

This may happen when there is an uncaught exception in the Future. Have you debugged your code? Try to put a debug break point right after response assignment and see if you actually are getting a response. This will help you to understand whether your code works at all.

PS. Side note: do not pr.show() / hide(); or showSimpleFlushbar(context, 'Successful'); in the function. These belong to the builder part of the FutureBuilder because these have to deal with redrawing the widget tree. Best case it that those code lines won't work, worst case that they give you weird errors.

Can you try adding the code

Future.delayed(Duration.zero, () {
          WidgetsBinding.instance.addPostFrameCallback((_) async{
            
            futureDashboard = dashboardData();
          }
          );
        });

to initState without the Future.delayed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM