简体   繁体   English

无法在 Flutter 中设置状态 ()

[英]Unable to SetState() in Flutter

AppScreenC will give all the installed apps in a ListView AppScreenC将在ListView中提供所有已安装的应用程序

class AppScreenC extends StatefulWidget {
  @override
  _AppScreenCState createState() => _AppScreenCState();
}

List<Application> apps;

getApps() async {
  if (apps == null) {
    apps = await DeviceApps.getInstalledApplications(
        onlyAppsWithLaunchIntent: true,
        includeSystemApps: true,
        includeAppIcons: true);
    apps.sort((a, b) => a.appName.compareTo(b.appName));
  }
}

ListView with all the installed apps are getting displayed in screen.包含所有已安装应用程序的 ListView 正在屏幕上显示。 I'm trying to change the icons based on onTap event.我正在尝试根据onTap事件更改图标。

But clicking on a list, icons are not changing.但是点击一个列表,图标并没有改变。

class _AppScreenCState extends State<AppScreenC> {
  final _app = <Application>[];
  @override
  Widget build(BuildContext context) {
    return _buildApps();
  }

  Widget _buildApps() {
    getApps();
    return ListView.builder(itemBuilder: (BuildContext context, int index) {
      _app.addAll(apps);
      return _buildRow(_app[index]);
    });
  }

  Widget _buildRow(ApplicationWithIcon app) {
    bool selected = false;
    return ListTile(
      leading: Image.memory(app.icon, height: 40),
      trailing:
          Icon(selected ? Icons.check_circle : Icons.check_circle_outline),
      title: Text(app.appName),
      onTap: () {
        selected = !selected;
        // print("$selected");
        // print("${app.apkFilePath}");
        setState(() {});
      },
    );
  }
}

itemCount: missing in ListView.Builder itemCount: ListView.Builder中缺少

   Widget _buildApps() {
        getApps();
        return ListView.builder(itemBuilder: (BuildContext context, int index) {
          _app.addAll(apps);
          return _buildRow(_app[index]);
        }, itemCount: _app.length);
     }

Also,还,

class _AppScreenCState extends State<AppScreenC> {
bool selected = false; // this should be at the top as it will persist the value
class _AppScreenCState extends State<AppScreenC> {

bool selected = false;

  Widget _buildRow(ApplicationWithIcon app) {
  //bool selected = false; not here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM