DeviceApps.getInstalledApplications() 返回一个List<Application>,我们可以用它来绘制我们的ListView:
Widget _buildListView() {
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
Application app = _apps[index];
return Column(
children: <Widget>[
ListTile(
onTap: () => DeviceApps.openApp(app.packageName),
title: Text('${app.appName} (${app.packageName})'),
),
Divider()
],
);
},
itemCount: _apps.length);
}
我们可以通过覆盖StatefulWidget 的initState 方法在初始化状态后立即加载已安装的应用程序:
List<Application> _apps = [];
@override
void initState() {
super.initState();
_loadApps();
}
Future<void> _loadApps() async {
List<Application> applications = await DeviceApps.getInstalledApplications();
setState(() => _apps = applications);
}
Widget _buildListView() {
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
Application app = _apps[index];
return Column(
children: <Widget>[
ListTile(
onTap: () => DeviceApps.openApp(app.packageName),
title: Text('${app.appName} (${app.packageName})'),
),
Divider()
],
);
},
itemCount: _apps.length);
}
这样,我们也可以轻松地使用GestureDetector 重新加载已安装的应用程序:
Widget _buildRefreshButton() {
return GesetureDetector(
onTap: () async { await _loadApps(); }
child: Text("Reload apps")
);
}
最好的解决方案是在卸载/安装应用时收到通知,但不幸的是,该软件包尚不支持此功能。
一个 hacky 解决方法是通过 Timer.periodic 轮询上面的 _loadApps(),但是,出于性能和用户体验的原因,不建议这样做。