Flutter中关于使用异步时,获得Future中数据的问题

使用异步获得Future

在flutter项目中使用async await异步获取数据时,会返回一个Future类型的数据,然而将其使用在widget中,会有一个问题:在statefulWidget中使用变量接收值,会出现无法赋值的情况

///index.dart
  class Index extends StatefulWidget {

  Index({Key key}) : super(key: key);

  @override

  _IndexState createState() => _IndexState();

}

 class _IndexState extends State {

  List _temps;

  String _studentId = "abcd";

  String _token =

      "lkjncasfmalknfadwSadwawf1dawd";

  @override

  void initState() {

    super.initState();

    _temps = _getClassItems(getOneDaylessons(_dates, _studentId, _token));

  }

  var _dates = initDate();

  void _getDates(value) {

    _dates = DateFormat('EEE', "en_US").format(value).toString();

    setState(() {

      _temps = _getClassItems(getOneDaylessons(_dates, _studentId, _token));

    });

  }

  List _getClassItems(List classItems) {

    if (classItems.isEmpty) {

      return [

        Container(

          height: 60,

          child: Center(

            child: Text("今日暂无课程"),

          ),

        )

      ];

    } else {

      return classItems;

    }

  }
  
   @override

  Widget build(BuildContext context) {
    return Scaffold(

      body: Container(

        child:
                  Column(

                    children: _temps,//报错处

                  ),
                 )
            )
   }
  
///getOneDaylessons.dart
  List getOneDaylessons(String date, String studentId, String token) {

  ClassResponseData _data;
  getTimeTableFromStudentID(studentId, token)

      .then((v) => {_data=v});

  List datas =

      getADayClasses(data);

  List temp = datas

      .map((e) {

        if (e.date == date) {

          return ClassItem(data: e);

        }

      })

      .toList()

      .where((element) => element != null)

      .toList();

  return temp;

}

//运行项目报错_temps是null

解决方案

将getOneDaylessons同样使用async包装,返回Future到index.dart.在index.dart中,使用FutureBuilder,取值

///getOneDaylessons.dart
Future> getOneDaylessons(
    String date, String studentId, String token) async {
  ClassResponseData response =
      await getTimeTableFromStudentID(studentId, token);
  List datas = getADayClasses(response);

  List temp = datas
      .map((e) {
        if (e.date == date) {
          return ClassItem(data: e);
        }
      })
      .toList()
      .where((element) => element != null)
      .toList();
  return temp;
}
///index.dart
...
_temps = _getClassItems();
...
Future> _getClassItems() async {
    List classItems =
        await getOneDaylessons(this._dates, this._studentId, this._token);
    if (classItems.isEmpty) {
      return [
        Container(
          height: 60,
          child: Center(
            child: Text("今日暂无课程"),
          ),
        )
      ];
    } else {
      return classItems;
    }
  }
 @override

  Widget build(BuildContext context) {
    return Scaffold(

      body: Container(

        child:
                  Container(
                    child: FutureBuilder(
                        future: _temps,
                        builder:
                            // ignore: missing_return
                            (BuildContext context, AsyncSnapshot snapshot) {
                          if (snapshot.connectionState ==
                              ConnectionState.done) {
                            if (snapshot.hasError) {
                              return Text(snapshot.error.toString());
                            }
                            return Column(children: snapshot.data);
                          }
                          return CircularProgressIndicator();
                        }),
                  ),
                 )
   }

你可能感兴趣的:(dartflutter)