Home > Back-end >  Component building before async function in Flutter
Component building before async function in Flutter

Time:11-10

I want to check if the client contains an id, and find out if it is logged in or not, to modify it when the widget returns, but it always stops at SharedPrefences and executes the Build, returning the address as false, even though it is logged.

class _ScheduleStateService extends State<ScheduleService> {

int clientId = 0;


//constructor

_ScheduleStateService(this.roboSelecionado) {
    _userAuthenticated();
  }

Future _userAuthenticated() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
      clientId = pref.getInt("cliente_id") ?? 0;
  }

}

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: const Text('Agendamento'),
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          children: 
            (clientId != 0)
                ? Column(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(8),
                        child: Card(
                          elevation: 4,
                          child: SizedBox(
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: TextFormField(
                                keyboardType: TextInputType.text,
                                controller: enderecoController,
                                decoration: const InputDecoration(
                                    labelText: 'Endereço',
                                    enabled: false,
                                    border: InputBorder.none,
                                    labelStyle: TextStyle(
                                        color: Color(0xFFE84505),
                                        fontSize: 18,
                                        fontWeight: FontWeight.w600)),
                              ),
                            ),
                          ),
                        ),
                      )
                    ],
                  )
                : Column(),

I know it's something related to Fure, Async and Await, but so far I couldn't find the solution!

CodePudding user response:

You need to call setState when you want the widget to be rebuilt in response to a change in state:

Future<void> _userAuthenticated() async {
    SharedPreferences pref = await SharedPreferences.getInstance();

    // Never call setState after an asynchronous gap without
    // ensuring that the widget is still mounted. Calling setState
    // on an unmounted widget will cause an exception to be thrown!
    if (!mounted) {
        return;
    }

    setState(() {
        clientId = pref.getInt("cliente_id") ?? 0;
    });
  }
}

You should also execute this type of action from initState, rather than from the constructor:

_ScheduleStateService(this.roboSelecionado);

@override
void initState() {
  super.initState();

  _userAuthenticated();
}
  • Related