Display Future variable on an Elevatedbutton

Asked

Viewed 30 times

0

I am making the call in my database of the boarding number, I need to put this number inside a button, but my variable "boarding" appears as undefined inside the Elevatedbutton

import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'Embarque.dart';
import 'Settings.dart';
import 'database/sqlite/connection.dart';

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

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

String num_embarque = "";

void main() async {
    Database db = await Connection.get;
    String url = 'SELECT nr_embarque FROM embarque';

    List nr_embarque = await db.rawQuery(url);
          num_embarque = nr_embarque.first["nr_embarque"];

  }


class _menuState extends State<menu> {
  @override
  Widget build(BuildContext context) {
    
    new Container();
    return Scaffold(
        appBar: AppBar(
          brightness: Brightness.dark,
          automaticallyImplyLeading: false,
          title: Text("Embarques"),
          backgroundColor: Color(0xffb0000CD),
        ),
        body: Container(
          padding: EdgeInsets.all(32),
          decoration: BoxDecoration(color: Colors.grey[400]),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              ConstrainedBox(
                constraints: BoxConstraints.tightFor(width: 1000, height: 50),
                child: ElevatedButton(
                  child: Text(
                    "Embarque: $num_embarque",
                    textAlign: TextAlign.center,
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                  ),
                  style: ElevatedButton.styleFrom(
                    primary: Color(0xffbDCDCDC),
                    onPrimary: Colors.black,
                  ),
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => Embarque(),
                      ),
                    );
                  },
                ),
              ),
              SizedBox(
                height: 32,
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => Settings(),
              ),
            );
          },
          child: const Icon(Icons.settings),
          backgroundColor: Color(0xffb0000CD),
        ));
  }
}

1 answer

0

The variable is undefined because it was not defined in the scope you are trying to use it. If you declare a variable within a function, it will only be visible to that function:

void funcao(){
String variavel = "123";
}
print(variavel); // erro

That’s what you did. The variable String num_embarque was defined within the function chamaemb(). To circumvent this error, you must set this variable in its state class, and from within the function just change its value:

class _menuState extends State<menu> {
  String num_embarque = ""; //Aqui a declaração da variavel
  @override
  Widget build(BuildContext context) {
[...]
       num_embarque = nr_embarque.first["nr_embarque"]; // Aqui você muda seu valor

If you want to know more about this subject, you can search for scope here on the site that returns some interesting answers.


Now that you’ve answered the question itself, a remark: The way you put your code, the function chamaemb will never be called. It is only declared within the build method. That alone should no longer be done. The build function should be used only for building the widget in question.

Even if, hypothetically, you called the function chamaemb within its function, it would be called every time the screen was rebuilt, which is probably not your intention. If it is an asynchronous function, you probably won’t be able to get the result between the function call and the time your result is used.

There are a few ways to do this, but a simple one is 1) define this function chamaemb out of the build method (as shown with the question variable). 2) In the initState method, call this function. 3)When arriving the desired result, remember to call the setState(). This way the screen will redesign when the result arrives. Another way to get what you want is by using a Futurebuilder.

  • I changed the way of declaring the variable as you said and change the value of it later, but at the time of displaying is returning null, IE, the change I make occurs only within my async method... I’m doing it this way:

  • edited the question and put the updated code

  • @Igor, the observations I made stick. Because you called the function main()? Where are you calling her? If you don’t call her, she will never perform. And if you don’t use the setState(), it will never update the screen when finished. Better read the second part of my question, and try that official Google codelab if you want a more practical example. If you have any questions, punctual and objective, can edit here or do another on the site.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.