简体   繁体   中英

I am trying to create a list view with the data that I got from API

class Search extends StatefulWidget {

  int id;
  Search([this.id]);

  @override
  _SearchState createState() => new _SearchState();

}  
class _SearchState extends State<Search> {


  @override
  void initState() {
    super.initState();
  }

  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    widget.id;

return new Scaffold(

      appBar: new AppBar(

        actions: <Widget>[

          new IconButton(
              icon: new Icon(Icons.exit_to_app),
              onPressed: _getTicketDetails
          ),


        ],
        centerTitle: true,
        title: new Text
          ("TicketsDetails", style: const TextStyle(
          fontFamily: 'Poppins'
          ,),
        ),

      ),

  );
  }

   _getTicketDetails() async {
    print(widget.id);
    var userDetails = {};
    final response = await http.get(
        "https....", headers: {
      HttpHeaders.AUTHORIZATION: access_token
    });

    List returnTicketDetails = json.decode(response.body);

    print(returnTicketDetails);

    for (var i = 0; i < (returnTicketDetails?.length ?? 0); i++) {
      final ticketresponse = await http.get(
          "https:...
              .toString()}", headers: {
        HttpHeaders.AUTHORIZATION:
        access_token
      });

      userDetails[returnTicketDetails[i]["user_id"]] =
          json.decode(ticketresponse.body);
    }
    print(userDetails);

  }

}

I would like to display in a Listview the index of my userDeatails, however for some reason the compiler does not recognise the userDetails, hence it highlight it as an error. I have done this before, but I don't get why I am encountering this issue now.

At the moment when I run it only display the appBar

As mentioned in the comments, your userDetails variable is scoped inside the _getTicketDetails method. You need to declare it outside of that method if you want it visible to the rest of your class:

var userDetails = {}; // Moved outside

_getTicketDetails() async {
  ...
}

Though note that you should also call setState when you modify this variable so that Flutter knows that this widget has changed and needs to be rebuild/rendered.

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