简体   繁体   English

如何从 function 获取价值并在文本小部件 flutter 中显示

[英]how to get value from function and display in text widget flutter

 import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: const RootPage(),
    );
  }
}

class RootPage extends StatefulWidget {
  const RootPage({super.key});

  @override
  State<RootPage> createState() => _RootPageState();
}

class _RootPageState extends State<RootPage> {
  int value = 75;
  Timer? _timer;
  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void valuerandomer() {
    _timer = Timer.periodic(
      Duration(milliseconds: 500),
      (t) {
        int count = 0;
        int max = 1000;
        int min = 1;
        Random rnd = new Random();
        while (count != -1) {
          count++;
          value += rnd.nextInt(6) + (-5);
        }
        if (value > (max - 1)) {
          value = 999;
        } else if (value < 0) {
          value = 0;
        }
        print(value);
        setState(() {});
      },
    );
  }

  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255, 12, 12, 12),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Stack(
            alignment: Alignment.center,
            children: [
              Image.asset('images/SQUARE.png'),
              Center(
                child: Text(
                  '$valuerandomer()',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      color: Color.fromARGB(255, 255, 106, 0),
                      fontSize: 90,
                      fontFamily: "MyFont"),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

The output of the code: output的代码: 在此处输入图像描述

I want the function to print every 500 miliseconds in the text widget so the value parameter starts with the value of 75 and changes every 500 milliseconds with this function.我希望 function 在文本小部件中每 500 毫秒打印一次,因此 value 参数从值 75 开始,并使用此 function 每 500 毫秒更改一次。 How do I do that?我怎么做? How do I declare this function in the text widget like Text('$valuerandomer')?如何在 Text('$valuerandomer') 等文本小部件中声明此 function? cuz its just dont work.因为它只是不工作。 I tried just to type there $value but still doesnt work.我试着在那里输入 $value 但仍然不起作用。

It says void function because your function returns void type void valuerandomer() .它说void function因为您的 function 返回 void 类型void valuerandomer() Try changing it to String valuerandomer and return your value at the end of the function.尝试将其更改为String valuerandomer并在 function 的末尾返回您的值。

You wrote that your value has to change but it's not really clear how it should change and what your valuerandomer tries to do.您写道,您的价值必须改变,但并不清楚它应该如何改变以及您的valuerandomer试图做什么。

My guess is that your are trying to randomize a number between min and max .我的猜测是您正在尝试在minmax之间随机化一个数字。 And this should happen count times.这应该发生count

EDIT: This code now runs forever and changes the number.编辑:此代码现在永远运行并更改数字。

 import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: const RootPage(),
    );
  }
}

class RootPage extends StatefulWidget {
  const RootPage({super.key});

  @override
  State<RootPage> createState() => _RootPageState();
}

class _RootPageState extends State<RootPage> {
  
  ValueNotifier<int> valueNotifier = ValueNotifier(75);
  late final Timer? _timer;
  final Random rnd = Random();
  final Duration duration = const Duration(milliseconds: 500);
  final int max = 1000;
  final int min = 1;

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    valuerandomer();
  }

  void valuerandomer() {
    _timer = Timer.periodic(
      duration,
      (Timer t) {
        int value = rnd.nextInt(max-min) + min;
        valueNotifier.value = value;
      },
    );
  }

  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255, 12, 12, 12),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Stack(
            alignment: Alignment.center,
            children: [
              Center(
                child: ValueListenableBuilder<int>(
                  valueListenable: valueNotifier,
                  builder: (context, value, child) {
                    return Text(
                      '$value',
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        color: Color.fromARGB(255, 255, 106, 0),
                        fontSize: 90,
                        fontFamily: "MyFont"),
                    );
                  }
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

First of all we call valueRandomer to start the timer.首先我们调用 valueRandomer 来启动计时器。 The method itself does nothing else.该方法本身不做任何其他事情。 The timer calls the callback function every 0.5 seconds.定时器每 0.5 秒调用一次回调 function。 Inside the callback function we generate a random number between min and max .在回调 function 中,我们生成一个介于minmax之间的随机数。

The rnd.nextInt(num) actually just generates number between 0 and num . rnd.nextInt(num)实际上只生成 0 和num之间的数字。 That's why we need interval shifting.这就是我们需要间隔移位的原因。 Substract by min to get the range between 0 and (max-min).减去min得到 0 和 (max-min) 之间的范围。 After that we add min back to number to get our real random number in our range.之后,我们将min添加回 number 以获得我们范围内的真实随机数。

Finally we set the value of the ValueNotifier to the newly generated number.最后我们将 ValueNotifier 的值设置为新生成的数字。 ValueNotifier and ValueListenableBuilder are pretty handy in this case.在这种情况下,ValueNotifier 和 ValueListenableBuilder 非常方便。 The ValueListenableBuilder rebuilds itself whenever the ValueNotifier changes its value.每当 ValueNotifier 更改其值时,ValueListenableBuilder 都会自行重建。 We dont need to call setState here anymore because ValueListenableBuilder handles that for us.我们不再需要在这里调用 setState,因为 ValueListenableBuilder 会为我们处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM