Why do I lose value of variable?

Asked by At

I am passing a value from a previous Stateful Widget screen into another Stateful Widget screen. Why am I am losing the value of searchTermID once it gets to the point after it calls the constructor?

class DetailScreen extends StatefulWidget {
  final int searchTermID;
  final String searchTerm;
  DetailScreen({Key key, @required this.searchTermID, this.searchTerm})
      : super(key: key);

  @override
  _DetailScreenState createState() =>
  _DetailScreenState(searchTermID: searchTermID, searchTerm: searchTerm);
}

class  _DetailScreenState extends State<DetailScreen>  {
  static int searchTermID;
  static String searchTerm;

  _DetailScreenState({searchTermID, searchTerm});

searchTermID being nulled out here forward

List data = getSWData(searchTermID) as List; //edited line

  static Future<List> getSWData(searchTermID) async {
    var res = await http.get(Uri.encodeFull("http://URLTOAPI" + searchTermID.toString()),
    headers: {"Accept": "application/json"});
    return json.decode(res.body);


}

1 Answers

0
Md Nazmul Amin On Best Solutions

Instead of this

class  _DetailScreenState extends State<DetailScreen>  {
  static int searchTermID;
  static String searchTerm;

  _DetailScreenState({searchTermID, searchTerm});
searchTermID being nulled out here forward

List data = getSWData(searchTermID) as List; //edited line

  static Future<List> getSWData(searchTermID) async {
    var res = await http.get(Uri.encodeFull("http://URLTOAPI" + searchTermID.toString()),
    headers: {"Accept": "application/json"});
    return json.decode(res.body);


}

Try like this. To access the value from stateful class to its state class use widget

class  _DetailScreenState extends State<DetailScreen>  {


List data = getSWData(widget.searchTermID) as List; //edited line

  static Future<List> getSWData(widget.searchTermID) async {
    var res = await http.get(Uri.encodeFull("http://URLTOAPI" + widget.searchTermID.toString()),
    headers: {"Accept": "application/json"});
    return json.decode(res.body);
}