每当按下按钮时如何更新文本字段

How to update a field of text whenever a button is pressed in flutter

问题: 我试图让一个古老的“gae”在按下按钮时更新到列表中的随机变量。不幸的是,它一直将 gae 定义为局部变量,使其无法工作。 我尝试过的: 将其放在单独的 class 中, 将变量移动一吨左右, 各种Return gae;和 setState 语句, 关于堆栈溢出相关主题的各种答案, 代码:

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

在此先感谢您的帮助

问题是程序无法访问变量

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'),
            ),
      ),

我的解决方案: // 在列表中为您的字符串创建索引

late int index;

在onPressed中,你会根据随机数改变索引

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

并且它会根据索引值生成和更改字符串

Text(list[index])

//最终代码

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])