尝试显示来自 void/string 的文本并从函数中获取“Closure: (dynamic) => void?

Trying to show text from void/string and getting "Closure: (dynamic) => void from Function?

因此,我正在尝试在其他脚本文件中显示我的空隙中的文本。我没有收到任何错误,但我确实收到了一些消息而不是显示的文本。 (关闭:(动态)=> void from Function "rannn":. Tasks)

任何人都可以帮助我如何解决此问题以便它显示文本?

这是我的代码

class TaskData extends ChangeNotifier {
  List<Task> _tasks = [
    Task(name: "Task one"),
    Task(name: "Task two"),
    Task(name: "Task three"),
  ];

  UnmodifiableListView<Task> get tasks {
    return UnmodifiableListView(_tasks);
  }

  void rannn(String) async {
    var randomItem = (_tasks.toList()..shuffle()).first.name;
    print(randomItem);
    //notifyListeners();
  }

在此处输入代码

Widget build(BuildContext context) => Container(
        color: Colors.transparent,
        child: Scaffold(
          //backgroundColor: Colors.transparent,
          backgroundColor: Colors.blue,
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                //SizedBox(height: 10),
                Text(
                  "${Provider.of<TaskData>(context).rannn} Tasks",
                ),
                //SizedBox(height: 10),//puts empty box to space things out
                buildTimer(),
                //const SizedBox(height: 10),
                buildButtons(),
              ],
            ),
          ),
        ),
      );

非常感谢!

定时器添加代码

class SecondRoute extends StatefulWidget {
  @override
  CustomMainPageState createState() => CustomMainPageState();
}

class CustomMainPageState extends State<SecondRoute> {
      static const maxSeconds = 5;
      int seconds = maxSeconds;
      Timer? timer;
    
      void resetTimer() => setState(() => seconds = maxSeconds);
    
      void startTimer({bool reset = true}) {
        if (reset) {
          resetTimer();
        }
        timer = Timer.periodic(Duration(seconds: 1), (_) {
          //add here instead seconds say minutes/miliseconds
          if (!mounted) // Putting this line of code with return under, fixed my issue i been having about mounted
            return;
          else if (seconds > 0) {
            setState(() => seconds--);
          } else {
            stopTimer(reset: false);
          }
        });
      }
    
      void stopTimer({bool reset = true}) {
        if (reset == mounted) {
          resetTimer();
        }
        setState(() => timer?.cancel());
      }
    
      Widget build(BuildContext context) => Container(
            color: Colors.transparent,
            child: Scaffold(
              //backgroundColor: Colors.transparent,
              backgroundColor: Colors.blue,
              body: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    FutureBuilder(
                      future: Provider.of<TaskData>(context).rann(),
                      builder: (context, snapshot) {
                        return Text(
                          "${snapshot.data}",
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 35,
                              fontWeight: FontWeight.w700),
                        );
                      },
                    ),
                    //SizedBox(height: 10),
                    //SizedBox(height: 10),//puts empty box to space things out
                    buildTimer(),
                    //const SizedBox(height: 10),
                    buildButtons(),
                  ],
                ),
              ),
            ),
          );
    
      @override
      Widget buildButtons() {
        final isRunning = timer == null ? false : timer!.isActive;
        final isCompleted = seconds == maxSeconds || seconds == 0;
        return isRunning || !isCompleted
            ? Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  ButtonWidget(
                    text: isRunning ? "Pause" : "Resume",
                    onClicked: () {
                      if (isRunning) {
                        stopTimer(reset: false);
                      } else {
                        startTimer(reset: false);
                      }
                    },
                  ),
                  const SizedBox(width: 12),
                  ButtonWidget(text: "Cancel", onClicked: stopTimer)
                ],
              )
            : ButtonWidget(
                text: "Start Timer!",
                color: Colors.black,
                backgroundColor: Colors.white,
                onClicked: () {
                  startTimer();
                },
              );
      }
    
      Widget buildTimer() => SizedBox(
            width: 200,
            height: 200,
            child: Stack(
              fit: StackFit.expand,
              children: [
                CircularProgressIndicator(
                  value: seconds / maxSeconds,
                  //if you delete 1 - then it goes to other direction
                  valueColor: AlwaysStoppedAnimation(Colors.white),
                  strokeWidth: 12,
                  backgroundColor: Colors.greenAccent,
                ),
                Center(child: buildTime()),
              ],
            ),
          );
    
      Widget buildTime() {
        if (seconds == 0) {
          return Icon(Icons.done, color: Colors.greenAccent, size: 112);
        } else {
          return Text(
            "$seconds",
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.white,
              fontSize: 80,
            ),
          );
        }
      }
    }

你做错了三件事。

首先:void rannn(String) 是一个函数,如果您只是尝试打印一个函数,您将得到您现在得到的结果。

其二:void rannn(String)是void函数,不会return一个Future<String>给你显示。您应该从中 return 一个字符串,例如:

Future<String> rann() async {
  return (_tasks.toList()..shuffle()).first.name;
}

第三:您应该使用 () 调用函数以访问它的 return 值:

"${Provider.of<TaskData>(context).rannn()} Tasks",

问题是,这是一个 return 是 Future 的函数,所以它也不起作用。

解决方案是使用 FutureBuilder widget,这样您就可以将 Provider.of<TaskData>(context).rannn() 传递给它的 future 参数并等待 returned future 最终显示它在您的 Text 小部件中

示例:

Future<String> rannn() async {
  await Future.delayed(const Duration(seconds: 2)); // Just so you can see the Future loading
  return (_tasks.toList()..shuffle()).first.name;
}


Widget build(BuildContext context) => Container(
  color: Colors.transparent,
  child: Scaffold(
    backgroundColor: Colors.blue,
    body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          FutureBuilder(
            future: Provider.of<TaskData>(context).rannn(),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return const Text('Loading...');
              }
              return Text('${snapshot.data}');
            },
          ),
        ],
      ),
    ),
  ),
);