dart Flutter:如何在另一个文件中的onClicked中访问此变量?(静态不起作用)

ymdaylpp  于 2023-06-19  发布在  Flutter
关注(0)|答案(1)|浏览(130)

我只学了4天的编程,我想做一个非常基本的名言生成应用程序。我有一个变量currentQuote,它在包含按钮的文件中的onPressed下被调用。在下面的代码中:

import 'package:flutter/material.dart';
import 'package:daily_quotes/random_quote.dart';

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

  @override
  State<ButtonQuote> createState() => _ButtonQuoteState();
}

class _ButtonQuoteState extends State<ButtonQuote> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(top: 50),
      child: Center(
        child: Column(
        children: [
          TextButton(onPressed: () {
            RandomQuote().currentQuote;
          }, 
          style: TextButton.styleFrom(
            foregroundColor: Colors.black,
            backgroundColor: Colors.red,
            textStyle: const TextStyle(fontSize:30),
          ),

          child: const Text("New Quote")
          )
        ],
          ),
      ));
  }
}

然后我有另一个文件处理随机生成。我只是让它生成一个1到10之间的数字,并在控制台中的setState下打印出来。在我添加图像和文本之前进行测试,这取决于生成的数字。如下图所示。

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

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

  @override
  State<RandomQuote> createState() => _RandomQuoteState();
}

class _RandomQuoteState extends State<RandomQuote> {
  static var currentQuote = 1;
  final ranNum = Random();

  void quoteGen() {
    var generation = ranNum.nextInt(10) + 1;
    setState(() {
      currentQuote = generation;
      print("$currentQuote");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          ButtonQuote(),
        ],
      ));
  }
}

问题就出在下面这个。首先,我似乎把'RandomQuote()'搞错了,应该是'_RandomQuoteState().currentQuote;'但是两个选项都显示错误。

TextButton(onPressed: () {
            RandomQuote().currentQuote;
          },

使用_RandomQuoteState时,我得到错误The method '_RandomQuoteState' isn 't defined for the type '_ButtonQuoteState'。尝试将名称更正为现有方法的名称,或定义名为“_RandomQuoteState”的方法。

hpxqektj

hpxqektj1#

如果我对您的问题理解正确的话,您希望从ButtonQuote小部件中的方法访问currentQuote变量。因此,要从外部访问您的Stateful Widget方法,您可以尝试以下操作:

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

  /// This line is responsible for access.
  static RandomQuoteState? of(BuildContext context) => context.findAncestorStateOfType<RandomQuoteState>();

  @override
  State<RandomQuote> createState() => RandomQuoteState();
}

然后在RandomQuoteState中创建一些你想要访问的变量或方法:

class RandomQuoteState extends State<RandomQuote> {
...
    ///  Variable or method you want to access.
    var currentQuote = 1;
...
}

现在,您可以从其他小部件访问currentQuote

TextButton(
  onPressed: () {
     ///  Variable or method you want to access.
    RandomQuote(context)?.currentQuote;
  },
child: const Text("Save"),
)

相关问题