CJW
CJW

Reputation: 990

Access variable built in different file/class

I have file.a which contains an array:

final _likes = <String>[];

Based on answers selected by the user, items are added to this array.

I want to then be able to, at the press of a button, display the items in the array to the user.

The issue is that the button I want the users to press is defined in file.b (as the Icon is on the AppBar).

How can I give file.b the ability to see the variable _likes and access the data in it, when it lives in file.a?

file.a:

import 'package:flutter/material.dart';
import './main.dart';

class Images extends StatefulWidget {
  @override
  _ImagesState createState() => _ImagesState();
}

class _ImagesState extends State<Images> with SingleTickerProviderStateMixin {
AnimationController _controller;
  Animation _animation;

  @override
  // ignore: must_call_super
  void initState() {
    _controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 1),
    );
    _animation = Tween(
      begin: 0.0,
      end: 1.0,
    ).animate(_controller);
  }

  @override
  dispose() {
    _controller.dispose();
    super.dispose();
  }

  int index = 0;

  final likes = <String>[];

  @override
  Widget build(BuildContext context) {
    _controller.forward();
    return GestureDetector(
      onHorizontalDragEnd: (DragEndDetails dragEndDetails) {
        if (dragEndDetails.primaryVelocity == 0) return;
        if (dragEndDetails.primaryVelocity.compareTo(0) == -1)
          setState(() {
            _controller.reset();
            dateIdeas.removeAt(index);
          });
        else
          setState(() {
            _controller.reset();
            likes.add(dateIdeas[index]['Description']);
            dateIdeas.removeAt(index);
          });
      },
      child: new Column(
        children: <Widget>[
          Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Column(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(left: 8.0, right: 8.0),
                    child: FadeTransition(
                      opacity: _animation,
                      child: Container(
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: Colors.pink[200],
                            width: 7,
                          ),
                          borderRadius: BorderRadius.circular(9),
                        ),
                        child: new Container(
                          child: new Image.asset(dateIdeas[index]['Image']),
                        ),
                      ),
                    ),
                  ),
                  Container(
                    alignment: Alignment.topCenter,
                    child: Text(dateIdeas[index]['Description'],
                        style: TextStyle(
                          fontSize: 30,
                          color: Colors.black,
                          fontFamily: 'IndieFlower',
                        )),
                  ),
                ],
              ),
            ],
          )
        ],
      ),
    );
  }
}

file.b:

import 'package:flutter/material.dart';
import './surprises.dart';
import './images.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SO Surprises',
      theme: ThemeData(
        primaryColor: Colors.pink[200],
      ),
      home: MyHomePage(title: ''),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
{



  int ideaCount = 1;

  int _swipeCount = 0;

  void _swipe() {
    setState(() {
      _swipeCount++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          Container(
            height: 150,
            width: 150,
            child: IconButton(
              icon: Image.asset('assets/images/SO.png'),
              padding:
                  const EdgeInsets.only(right: 40.0, top: 10, bottom: 10.0),
            ),
          ),
          GestureDetector(
            onTap: () => print(Images.likes),
            child: Padding(
              padding: const EdgeInsets.only(right: 10.0),
              child: Icon(
                Icons.star,
                color: Colors.white,// add custom icons also
              ),
            ),
          ),
        ],
      ),
      body: _swipeCount == 0
          ? Stack(
              children: <Widget>[
                GestureDetector(
                  onHorizontalDragEnd: (DragEndDetails dragEndDetails) {
                    if(dragEndDetails.primaryVelocity == 0) return;
                    _swipe();
                  },
                  child: Container(
                    color: Colors.transparent,
                    alignment: Alignment.center,
                    child: Text("Swipe to get started! $_swipeCount"),
                  ),
                ),
              ],
            )
          : Template(),
    );
  }
}

Upvotes: 1

Views: 56

Answers (1)

timilehinjegede
timilehinjegede

Reputation: 14033

By prefixing your likes list with an underscore (_), it means you are making that method only accessible inside the class it belongs too.

To be able to use the method in other parts of your program, remove the underscore(_).

After removing the _, you are making the likes list accessible from other parts of your code.

Upvotes: 1

Related Questions