Home > other >  Flutter - Text value does not get updated after ontap
Flutter - Text value does not get updated after ontap

Time:11-12

I am quite new to Flutter / Dart so I am trying to find out why my text does not get updated after I clicked the button. It does gets updated when I do a hot restart but it does not work when you press on the button.

Does anyone know why and what I could do? Even giving some tips if to use state or not or anything else.

class _CharacterCreateState extends State<CharacterCreate> {
  final _auth = FirebaseAuth.instance;

  String userText = "";

  @override
  Widget build(BuildContext context) {

    List _iconTypes = [
      {'icon': Icons.cake, 'name': 'cake'},
      {'icon': Icons.add, 'name': 'add'},
      {'icon': Icons.zoom_in_outlined, 'name': 'zoom_in_outlined'},
      {'icon': Icons.auto_awesome_motion, 'name': 'auto_awesome_motion'},
      {'icon': Icons.call_end_sharp, 'name': 'call_end_sharp'},
      {'icon': Icons.equalizer_rounded, 'name': 'equalizer_rounded'},
      {'icon': Icons.wifi_lock, 'name': 'wifi_lock'},
      {'icon': Icons.mail, 'name': 'mail'},
    ];

    return Scaffold(
      backgroundColor: Colors.white,
      body: ListView(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: GridView.builder(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 5,
                crossAxisSpacing: 5.0,
                mainAxisSpacing: 5.0,
              ),
              itemCount: _iconTypes.length,
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: () {
                    userText = _iconTypes[index]['name'];
                  },
                  child: Container(
                    child: Icon(_iconTypes[index]['icon']),
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.blueAccent)),
                  ),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: [
                Text(
                  "Your username is:",
                  style: TextStyle(fontSize: 20),
                ),
                Text(userText)
              ],
            ),
          ),
        ],
      ),
    );
  }

CodePudding user response:

You need to use a SetState for update build method and refresh the variables:

onTap: () {
    setState(() {
        userText = _iconTypes[index]['name'];
    });

},

If you dont want to use Setstate or Statefull widgets can use another control state like GetX

  • Related