API调用后有状态窗口小部件上的计时问题

时间:2017-07-14 16:27:29

标签: dart flutter

我遇到计时问题,我从api获取数据,然后从JSON创建列表。我想在结果列表视图中使用结果列表的长度作为项目计数。但是它会在itemcount上抛出null错误,然后完成处理并显示listview。我试图找到时间问题的位置以及如何处理项目和小部件,以便我可以避免错误。如果有人知道我的代码存在缺陷,我的代码就在下面。

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


}

1 个答案:

答案 0 :(得分:6)

在调用await方法时,您应该使用async。您可以将initState标记为async,它仍会覆盖。

确保在改变成员变量时调用setState()

如果您在异步等待后执行此操作,请在if (mounted)之前检查setState,因为该窗口小部件可能不再可见。

在执行异步编程时,请考虑使用FutureBuilder而不是setState