flutter timing problems on stateful widget after API call
我遇到了计时问题,我从 api 获取数据,然后从 JSON 创建一个列表。我认为使用结果列表的长度作为我的列表视图中的项目计数。但是,它会在 itemcount 上引发 null 错误,然后完成处理并显示列表视图。我试图找出时间问题出在哪里以及如何处理项目和小部件,以便避免错误。如果有人对我的代码有缺陷有任何想法,我的代码如下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | class Specialty extends StatefulWidget { Specialty({Key key, this.title}) : super(key: key); final String title; @override _SpecialtyState createState() => new _SpecialtyState(); } class _SpecialtyState extends State<Specialty> { bool _dataReceived = false; bool _authenticated = false; SharedPreferences prefs; List mylist; @override void initState() { super.initState(); _getPrefs(); _getSpecialty(); } _getPrefs() async { prefs = await SharedPreferences.getInstance(); _authenticated = prefs.getBool('authenticated'); print('AUTH2: ' + _authenticated.toString()); print('AUTHCODE2: ' + prefs.getString('authcode')); } _getSpecialty() async { var _url = 'http://$baseurl:8080/support/specialty'; var http = createHttpClient(); var response = await http.get(_url); var specialties = jsonCodec.decode(response.body); mylist = specialties.toList(); //_dataReceived = true; setState(() { _dataReceived = true; }); } Future<Null> _onRefresh() { Completer<Null> completer = new Completer<Null>(); Timer timer = new Timer(new Duration(seconds: 3), () { completer.complete(); }); return completer.future; } @override Widget build(BuildContext context) { return new Scaffold( body: new RefreshIndicator( child: new ListView.builder( itemBuilder: _itemBuilder, itemCount: mylist.length, ), onRefresh: _onRefresh, )); } Widget _itemBuilder(BuildContext context, int index) { Specialties spec = getSpec(index); return new SpecialtyWidget(spec: spec,); } Specialties getSpec(int index) { return new Specialties( mylist[index]['id'], mylist[index]['name'], mylist[index]['details'], new Photo('lib/images/' + mylist[index]['image'], mylist[index]['name'], mylist[index]['name'])); //return new Specialties.fromMap(mylist[index]); } var jsonCodec = const JsonCodec(); } |
您应该在调用
确保在你改变成员变量时调用
如果您在异步等待之后执行此操作,请在
在进行异步编程时考虑使用