【问题标题】:How to create a random Number Genertor in Flutter?如何在 Flutter 中创建随机数生成器?
【发布时间】:2021-10-31 17:07:33
【问题描述】:

我想知道如何创建一个随机数生成器。但不是通常,我想构建以下内容:

  • 在应用程序中应该有一个文本字段,用户可以在其中输入最小值和最大值 数字生成器。

  • 点击按钮后,应该有一个弹出窗口或修改后的 AlertDialog 打印结果

如果你能帮助我,我会很高兴。

【问题讨论】:

    标签: flutter button random numbers generator


    【解决方案1】:

    对于随机数:

    int MIN;
    int MIN;
    double randomNumber = random.nextInt(MAX) + MIN;
    

    对于文本字段: 您从文本字段中获取数据(例如使用文本字段 onSubmitted)并将其设置为最小值和最大值。

    对于弹出: // 可以设置标题和内容 使用AlertDialog(title: Text('Random number') , content: Text(randomNumber.toString()))

    例如,这可能是您想要的代码(只是一个示例,您可以随意更改):

    import 'package:flutter/material.dart';
    import 'dart:math';
    
    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: LoginScreen(),
        );
      }
    }
    
    class LoginScreen extends StatefulWidget {
      createState() {
        return new LoginScreenState();
      }
    }
    
    class LoginScreenState extends State<LoginScreen> {
      int min = 1;
      int max = 1;
      int randomNumber = 1;
      Widget build(BuildContext context) {
        return Scaffold(
          body: Column(
            children: [
              TextField(
                decoration: InputDecoration(labelText: 'Enter Min'),
                onSubmitted: (thisIsTheMinValueJustSubmitted) {
                  min = int.parse(thisIsTheMinValueJustSubmitted);
                },
              ),
              TextField(
                decoration: InputDecoration(labelText: 'Enter Max'),
                onSubmitted: (thisIsTheMaxValueJustSubmitted) {
                  max = int.parse(thisIsTheMaxValueJustSubmitted);
                },
              ),
              ElevatedButton(
                  onPressed: () {
                    setState(() {
                      randomNumber = Random().nextInt(max - min) + min;
                    });
                  },
                  child: Text('Generate Number')),
              AlertDialog(
                title: Text('Random Number is:'),
                content: Text(randomNumber.toString()),
              ),
              Text(randomNumber.toString()),
            ],
          ),
        );
      }
    }
    

    【讨论】:

    • 感谢您的回答。如果它对我有用,我会尝试并做出回应。
    • 如何将 onSubmitted 与 TestField 一起使用。那么如何将其设置为最小值和最大值?我对扑扑很陌生,所以我有点困惑。 @Benyamin
    • 我为你写了整个代码。只需检查一下。
    • 如果有效,则接受答案以关闭主题。
    • 很抱歉再次打扰您,但在尝试了一下后我发现,这些数字只是随机的,而不是基于最小值和最大值。例如,我复制了您的代码并运行了它。它会像它想要的那样输出数字。当我设置最小值为 20 和最大值为 30 时,它会打印 31 之类的数字; 49; 38; 2; 6. 所以它只是随机的。请帮忙
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 2012-06-09
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多