共计 2449 个字符,预计需要花费 7 分钟才能阅读完成。
应用异步取得 Future<T>
在 flutter 我的项目中应用 async await 异步获取数据时,会返回一个 Future<T> 类型的数据,然而将其应用在 widget 中,会有一个问题:在 statefulWidget 中应用变量接管值,会呈现无奈赋值的状况
///index.dart
class Index extends StatefulWidget {Index({Key key}) : super(key: key);
@override
_IndexState createState() => _IndexState();
}
class _IndexState extends State<Index> {
List<Widget> _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<Widget> _getClassItems(List<Widget> 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<Widget> getOneDaylessons(String date, String studentId, String token) {
ClassResponseData _data;
getTimeTableFromStudentID(studentId, token)
.then((v) => {_data=v});
List<ClassItemViewModel> 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<T> 到 index.dart. 在 index.dart 中,应用 FutureBuilder,取值
///getOneDaylessons.dart
Future<List<Widget>> getOneDaylessons(String date, String studentId, String token) async {
ClassResponseData response =
await getTimeTableFromStudentID(studentId, token);
List<ClassItemViewModel> 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<List<Widget>> _getClassItems() async {
List<Widget> 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();}),
),
)
}
正文完