dimanche 18 juin 2023

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({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")
          )
        ],
          ),
      ));
  }
}


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({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(),
        ],
      ));
  }
}

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'.




Aucun commentaire:

Enregistrer un commentaire