shanthosh
shanthosh

Reputation: 57

Unable to SetState() in Flutter

AppScreenC will give all the installed apps in a 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. I'm trying to change the icons based on onTap event.

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(() {});
      },
    );
  }
}

Upvotes: 1

Views: 107

Answers (2)

Raine Dale Holgado
Raine Dale Holgado

Reputation: 3460

class _AppScreenCState extends State<AppScreenC> {

bool selected = false;

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

Upvotes: 1

Jitesh Mohite
Jitesh Mohite

Reputation: 34210

itemCount: missing in 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

Upvotes: 1

Related Questions