简体   繁体   中英

How to access a function from a different dart file in Flutter?

This is my HomePage.dart Codes. Here I Want to access the _pushSaved() function into the 'onpressed' property from a different file named "randomwords.dart" file (code attached for review). It seems I need to declare the _pushSaved() somewhere but do not have any idea as I am new to dart and flutter. I Will be thankful if somebody could help. Thanks in advance.



class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("StartUp Name Generator"),
            actions: [
              IconButton(icon: Icon(Icons.list), **onPressed: _pushSaved**)
        ],
      ),
      body: RandomWords(),
    );
  }
}

The _pushSaved() function code in the randomwords.dart file needs to be accessed in the HomePage.dart as object...

class RandomWords extends StatefulWidget {
  @override
  _RandomWordsState createState() => _RandomWordsState();
}

class _RandomWordsState extends State<RandomWords> {
  final _suggestions = <WordPair>[];
  final _saved = Set<WordPair>();
  final _biggerFont = TextStyle(fontSize: 20.0, color: Colors.pink);
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (context, i) {
        if (i.isOdd) return Divider();

        final index = i ~/ 2;
        if (index >= _suggestions.length) {
          _suggestions.addAll(generateWordPairs().take(10));
        }
        return _buildRow(_suggestions[index]);
      },
    );
  }

  Widget _buildRow(WordPair pair) {
    final alreadySaved = _saved.contains(pair);
    return ListTile(
      title: Text(
        pair.asPascalCase,
        style: _biggerFont,
      ),
      trailing: Icon(
        alreadySaved ? Icons.favorite : Icons.favorite_border,
        color: alreadySaved ? Colors.red : null,
      ),
      onTap: () {
        setState(() {
          if (alreadySaved) {
            _saved.remove(pair);
          } else {
            _saved.add(pair);
          }
        });
      },
    );
  }

  void **_pushSaved()** {
    Navigator.of(context).push(
      MaterialPageRoute<void>(
        builder: (BuildContext context) {
          final tiles = _saved.map(
            (WordPair pair) {
              return ListTile(
                title: Text(
                  pair.asPascalCase,
                  style: _biggerFont,
                ),
              );
            },
          );

          final divided =
              ListTile.divideTiles(tiles: tiles, context: context).toList();

          return Scaffold(
            appBar: AppBar(
              title: Text("Saved Suggestions"),
            ),
            body: ListView(
              children: divided,
            ),
          );
        },
      ),
    );
  }
}

虽然上面的答案解决了你的问题,但这不是一个好习惯,使用抽象类来定义应该在不同地方使用的函数。

Your function is defined as a private property. You need to change that first.

pushSaved()

Secondly, You need to define this function as a static function to access it in other classes.

static void pushSaved()

Now call your function in your HomePage class in onPressed function like this:

onPressed: () => RandomWords.pushSaved

Import the HomePage.dart in the Homepage file like this;

import 'package:main.dart' as main; //it doesn't have to be as 'main'

and then acces the function like this:

IconButton(icon: Icon(Icons.list),*onPressed: main._pushSaved)

Note : now when I've done somthing like this and my function startes with a _ it unfortunantly doesn't work, I know that everyone makes functions with _ first, but apperantly it didn't work for me when importing it from another file. So beware of that. Also the function has to be out of the _RandomWordsState to be accesed by the other file. Just put it down underneath.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM