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

huangapple go评论60阅读模式
英文:

Flutter: How do I access this variable within onClicked in another file? (static doesn't work)

问题

I've only been learning flutter or programming at all for 4 days and I want to make a very basic famous quote generation app. I have a variable, currentQuote which is called under onPressed in the file that houses the button. In the below code:

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

class ButtonQuote extends StatefulWidget {
  const ButtonQuote({Key? 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")
          )
        ],
          ),
      ));
  }
}

I then have another file which handles the random generation. I've just made it generate a number between 1 and 10 and print in console under setState. For testing before I add images and text that depend on what number is generated. Shown below.

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

class RandomQuote extends StatefulWidget {
  const RandomQuote({Key? 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(),
        ],
      ));
  }
}

The problem lies in this below. First off it seems I've got 'RandomQuote()' wrong and it should be '_RandomQuoteState().currentQuote;'. However both options show an error.

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

With _RandomQuoteState I get the error:
The method '_RandomQuoteState' isn't defined for the type '_ButtonQuoteState'.
Try correcting the name to the name of an existing method, or defining a method named '_RandomQuoteState'.

英文:

I've only been learning flutter or programming at all for 4 days and I want to make a very basic famous quote generation app. I have a variable, currentQuote which is called under onPressed in the file that houses the button. In the below code:

import &#39;package:flutter/material.dart&#39;;
import &#39;package:daily_quotes/random_quote.dart&#39;;

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

  @override
  State&lt;ButtonQuote&gt; createState() =&gt; _ButtonQuoteState();
}

class _ButtonQuoteState extends State&lt;ButtonQuote&gt; {
  @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(&quot;New Quote&quot;)
          )
        ],
          ),
      ));
  }
}


I then have another file which handles the random generation. I've just made it generate a number between 1 and 10 and print in console under setState. For testing before I add images and text that depend on what number is generated. Shown below.

import &#39;package:flutter/material.dart&#39;;
import &#39;package:daily_quotes/regen_button.dart&#39;;
import &#39;dart:math&#39;;


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

  @override
  State&lt;RandomQuote&gt; createState() =&gt; _RandomQuoteState();
}

class _RandomQuoteState extends State&lt;RandomQuote&gt; {
  static var currentQuote = 1;
  final ranNum = Random();

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

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

The problem lies in this below. First off it seems I've got 'RandomQuote()' wrong and it should be '_RandomQuoteState().currentQuote;' However both options show an error.

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

With _RandomQuoteState I get the error
The method '_RandomQuoteState' isn't defined for the type '_ButtonQuoteState'.
Try correcting the name to the name of an existing method, or defining a method named '_RandomQuoteState'.

答案1

得分: 0

如果我正确理解你的问题,你想从ButtonQuote小部件中的方法中访问currentQuote变量。为了从外部访问你的Stateful Widget方法,你可以尝试这样做:

class RandomQuote extends StatefulWidget {
  const RandomQuote({Key? key});

  /// 这行代码负责访问。
  static RandomQuoteState? of(BuildContext context) => context.findAncestorStateOfType<RandomQuoteState>();

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

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

class RandomQuoteState extends State<RandomQuote> {
...
    ///  你想要访问的变量或方法。
    var currentQuote = 1;
...
}

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

TextButton(
  onPressed: () {
     ///  你想要访问的变量或方法。
    RandomQuote.of(context)?.currentQuote;
  },
  child: const Text("保存"),
)
英文:

If I understand your problem correctly you want to access the currentQuote variable from the method in the ButtonQuote widget.
So, to get access to your Stateful Widget methods from outside you can try this:

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

  /// This line is responsible for access.
  static RandomQuoteState? of(BuildContext context) =&gt; context.findAncestorStateOfType&lt;RandomQuoteState&gt;();

  @override
  State&lt;RandomQuote&gt; createState() =&gt; RandomQuoteState();
}

Then inside RandomQuoteState create some variable or method you want to access:

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

And now, you can get access to currentQuote from other widgets:

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

huangapple
  • 本文由 发表于 2023年6月19日 02:22:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定