为什么我失去变量的价值?

时间:2019-04-23 05:01:34

标签: flutter

我正在将值从先前的状态小部件屏幕传递到另一个状态小部件屏幕。为什么一旦搜索到构造函数之后,搜索术语ID就会丢失?

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在此处向前无效

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 个答案:

答案 0 :(得分:0)

代替此

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);


}

尝试这样。 要从有状态类访问其状态类的值,请使用小部件

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);
}