Search code examples
flutterdartsetstatelisttile

Flutter - codes not working correctly after putting inside setState


I am trying to add to an array list after user clicked. I am using InkWell, onTap function.

child: InkWell(
                  onTap: () {
                    if (tempArray.contains(entries[index].toString())) {
                      tempArray.remove(entries[index].toString());
                      print(tempArray.toList().toString());
                    } else {
                      tempArray.add(entries[index].toString());
                      print(tempArray.toList().toString());
                    }

My debug console is printing these out,

enter image description here

However, when i put the codes inside a setState, this is what got printed

                  child: InkWell(
                  onTap: () {
                    setState(() {
                      if (tempArray.contains(entries[index].toString())) {
                        tempArray.remove(entries[index].toString());
                        print(tempArray.toList().toString());
                      } else {
                        tempArray.add(entries[index].toString());
                        print(tempArray.toList().toString());
                      }
                    });

enter image description here

What i am trying to do, is to show/hide the 'trailing' icon in the ListTile, based on whatever user had selected the particular item.

My full codes (without the setState) are as follows,

import 'package:flutter/material.dart';
class Personal1Redo extends StatefulWidget {
@override
_Personal1RedoState createState() => _Personal1RedoState();
}
class _Personal1RedoState extends State<Personal1Redo> {
@override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);

List<String> entries = [
  'Residental Loan',
  'Personal Loan',
  'Car Loan',
  'Renovation Loan',
  'Savings Account',
];

List<String> tempArray = [];

final heading = Column(
  children: [
    const SizedBox(
      height: 40,
    ),
    SizedBox(
      height: (mediaQuery.size.height - mediaQuery.padding.top) * 0.1,
      child: const Align(
        alignment: Alignment.center,
        child: Text(
          'What do you aspire to do?',
          textAlign: TextAlign.center,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 20,
          ),
        ),
      ),
    ),
    const SizedBox(
      height: 20,
    ),
  ],
);

return Scaffold(
  appBar: AppBar(
    title: Text('Borrower redo'),
  ),
  body: SingleChildScrollView(
    child: Column(
      children: <Widget>[
        heading,
        ListView.builder(
            shrinkWrap: true,
            itemCount: entries.length,
            itemBuilder: (ctx, index) {
              return Container(
                width: mediaQuery.size.width * 0.9,
                padding: const EdgeInsets.all(15),
                child: InkWell(
                  onTap: () {
                    if (tempArray.contains(entries[index].toString())) {
                      tempArray.remove(entries[index].toString());
                      print(tempArray.toList().toString());
                    } else {
                      tempArray.add(entries[index].toString());
                      print(tempArray.toList().toString());
                    }
                  },
                  child: Card(
                    margin: const EdgeInsets.all(10),
                    elevation: 8,
                    child: ListTile(
                      title: Text(
                        entries[index],
                        style: TextStyle(
                          color: Colors.grey.shade800,
                          fontSize: 20,
                        ),
                        textAlign: TextAlign.center,
                      ),
                      trailing: tempArray.contains(entries[index])
                          ? Icon(Icons.check_box_outline_blank_outlined)
                          : null,
                    ),
                  ),
                ),
              );
            })
      ],
    ),
  ),
);
}
}

Any helps and guidance is very much appreciated, thanks!!


Solution

  • Define variables and functions outside build method. As setState method, calls build, every time it is called. Like this :

    import 'package:flutter/material.dart';
    class Personal1Redo extends StatefulWidget {
      @override
      _Personal1RedoState createState() => _Personal1RedoState();
    }
    
    class _Personal1RedoState extends State<Personal1Redo> {
      List<String> entries = [
        'Residental Loan',
        'Personal Loan',
        'Car Loan',
        'Renovation Loan',
        'Savings Account',
      ];
    
      List<String> tempArray = [];
    
      getHeadingWidget(BuildContext context) {
        return Column(
          children: [
            const SizedBox(
              height: 40,
            ),
            SizedBox(
              height: (mediaQuery!.size.height - mediaQuery.padding.top) * 0.1,
              child: const Align(
                alignment: Alignment.center,
                child: Text(
                  'What do you aspire to do?',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20,
                  ),
                ),
              ),
            ),
            const SizedBox(
              height: 20,
            ),
          ],
        );
      }
    
      
    
      @override
      Widget build(BuildContext context) {
       final mediaQuery = MediaQuery.of(context);
    
        return Scaffold(
          appBar: AppBar(
            title: Text('Borrower redo'),
          ),
          body: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                getHeadingWidget(context),
                ListView.builder(
                    shrinkWrap: true,
                    itemCount: entries.length,
                    itemBuilder: (ctx, index) {
                      return Container(
                        width: mediaQuery.size.width * 0.9,
                        padding: const EdgeInsets.all(15),
                        child: InkWell(
                          onTap: () {
                            if (tempArray.contains(entries[index].toString())) {
                              tempArray.remove(entries[index].toString());
                              print(tempArray.toList().toString());
                            } else {
                              tempArray.add(entries[index].toString());
                              print(tempArray.toList().toString());
                            }
                          },
                          child: Card(
                            margin: const EdgeInsets.all(10),
                            elevation: 8,
                            child: ListTile(
                              title: Text(
                                entries[index],
                                style: TextStyle(
                                  color: Colors.grey.shade800,
                                  fontSize: 20,
                                ),
                                textAlign: TextAlign.center,
                              ),
                              trailing: tempArray.contains(entries[index])
                                  ? Icon(Icons.check_box_outline_blank_outlined)
                                  : null,
                            ),
                          ),
                        ),
                      );
                    })
              ],
            ),
          ),
        );
      }
    }