2017-07-14 7 views
3

タイミングの問題が発生しています.APIからデータを取得してから、JSONからリストを作成しています。結果リストの長さをリストビューの項目数として使用すると思います。ただし、itemcountにNULLエラーをスローし、処理を完了してリストビューを表示します。私は、タイミングの問題がどこにあるのか、アイテムやウィジェットがどのように処理されてエラーを回避できるのかを見極めようとしています。誰かが私のコードに欠陥があるアイデアがあれば、私のコードは以下の通りです。API呼び出し後のステートフルウィジェットでのフラッタタイミングの問題

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://174.138.61.246: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(); 


} 
+0

このような目的のために設計されたFuturBuilderをご覧ください。 –

答えて

3

あなたasyncメソッドを呼び出すときは、awaitを使用する必要があります。 initStateasyncとマークできますが、それでも無効になります。

メンバ変数を変更するたびに必ずsetState()に電話してください。

if (mounted)の前に、setStateをチェックしてください。ウィジェットが表示されなくなる可能性があるため、非同期待機の後に実行してください。

非同期プログラミングを行うときにsetStateの代わりにFutureBuilderを使用することを検討してください。

関連する問題