Home > Back-end >  How to update a field of text whenever a button is pressed in flutter
How to update a field of text whenever a button is pressed in flutter

Time:05-12

The Problem: I'm trying to get a venerable "gae" to update to a random variable from a list whenever a button is pressed. Unfortunately it keeps define gae as a local variable making it unable to work. What I've Tried: Putting it in a separate class, Moving the variable around a ton, Various Return gae; and setState statements, Various answers on related topics on stack overflow, Code:

import 'package:flutter/material.dart';
import 'dart:math';

var list = [
  'one',
  'two',
];
var gae = 'enter something in the box then i can give you advice';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const MyStatefulWidget(),
      ),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TextFormField(
            decoration: const InputDecoration(
              hintText: 'what do you need help with?',
            ),
            validator: (String? value) {
              if (value == null || value.isEmpty) {
                return 'either you have no problems or that box is empty';
              }
              return null;
            },
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: ElevatedButton(
              onPressed: () {
                final _random = new Random();

// generate a random index based on the list length
// and use it to retrieve the element
                var gae = list[_random.nextInt(list.length)];
              },
              child: const Text('help me pls'),
            ),
          ),
          Text(gae)
          // ignore: unnecessary_new
        ],
      ),
    );
  }
}

Thanks in advance for any help

CodePudding user response:

The problem is the program cannot access to the variable

Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: ElevatedButton(
              onPressed: () {
                final _random = new Random();

                // cannot access this variable
                var gae = list[_random.nextInt(list.length)];
              },
              child: const Text('help me pls'),
            ),
      ),

My solution: // Create the index for your string in the list

late int index;

In the onPressed, you will change the index based on the random number

child: ElevatedButton(
              onPressed: () {
                final _random = Random();
                // generate a random index based on the list length
                // and use it to retrieve the element
                setState(() {
                  index = _random.nextInt(list.length);
                });
              },

And it will generate and change the String base on the index value

Text(list[index])

//Final code

Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: ElevatedButton(
              onPressed: () {
                final _random = Random();
                // generate a random index based on the list length
                // and use it to retrieve the element
                setState(() {
                  index = _random.nextInt(list.length);
                });
              },
              child: const Text('help me pls'),
            ),
          ),
          Text(list[index])
  • Related