0

how do I make a method inside Future class? I wanted to call the methods in other dart files, but because I made the functions as Future, it does not get called by the instance name.

This is the example code that I want to call in another dart file.

Future tokenDb() async{
  final database = openDatabase(
    join(await getDatabasesPath(), 'token_list.db'),
    onCreate: (db, version) {
      return db.execute(
        "CREATE TABLE tokens (token INTEGER PRIMARY KEY)",
      );
    },
    version: 1,
  );

  Future<void> insertToken(Token token) async {
    final Database db = await database;
    await db.insert(
      'tokens',
      token.toMap(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }
}

and I need it here:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  runApp(
    MaterialApp(home: MyApp()),
  );
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  late FirebaseMessaging messaging;
  String tokenValue = "";

  @override
  void initState() {
    messaging = FirebaseMessaging.instance;
    messaging.getToken().then((value) {
      tokenValue = value!;
      Clipboard.setData(ClipboardData(text: tokenValue));
      print(tokenValue);

      var user1 = Token(token: tokenValue);
      print("user1 token : " + tokenValue);

      **var db = tokenDb();
      db.insertToken(user1);
      tokenDb();**
// Maybe I need to call the function here?

    });
    super.initState();


  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: AuthTypeSelector(),
      ),
    );
  }
}

I don't have a lot of knowledge of Flutter... Thanks for your help!! I really appreciate it. :)

Kate Jo
  • 154
  • 1
  • 10
  • Does this answer your question? [What is a Future and how do I use it?](https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it) – nvoigt Sep 30 '21 at 09:32
  • @nvoigt I actually read that post before but don't think that answers all of my question :( maybe Future inside Future is not good and that's why I have no other references for it? – Kate Jo Sep 30 '21 at 09:38
  • 1
    @KateJo You can do `tokenDb().then((db) { db.insertToken(user1); }`, like you did before. However, you should avoid doing asynchronous work in `initState` and use a `FutureBuilder` instead. – jamesdlin Sep 30 '21 at 15:18

0 Answers0