Flutter Mobx load data at page start

Asked

Viewed 182 times

0

I am studying/learning about mobx, and I am like the following problem: I have a controller that picks up and saves some settings with Shared Preferences. The saving part of the data is working properly, but I was wanting to display the saved data when opening the configuration page, but when I open it even goes in the method(_fillTextoParam) that loads the config, but the data is not displayed in Textformfield

Controller code:

import 'package:acmil_frontend_flutter/app/shared/models/Parametros_Model.dart';
import 'package:acmil_frontend_flutter/app/shared/utils/Global_Scaffold.dart';
import 'package:mobx/mobx.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'repositories/configuracao_repository.dart';

part 'configuracao_controller.g.dart';

@Injectable()
class ConfiguracaoController = _ConfiguracaoControllerBase  with _$ConfiguracaoController;

abstract class _ConfiguracaoControllerBase with Store { 
  final ConfiguracaoRepository configuracaoRepository;

  String mensagemErro = ""; 

  @observable
  String url = "";

  @observable
  String empresa = "";

  _ConfiguracaoControllerBase (this.configuracaoRepository) {
     _preencherTextoParam();
  }

  @action
  setURL(String value) => url = value;

  @action
  setEmpresa(String value) => empresa = value;

  @action
  setMensagemErro(String value) => mensagemErro = value;

  @action
  validarCampos() {

    if(url.isNotEmpty){
      if( empresa.isNotEmpty ){        
        _testarConexaoApi();

      }else{
        mensagemErro = "Preencha o codigo da empresa padrão!";
        GlobalScaffold.instance.showSnackBarErro(mensagemErro);
      }

    }else{
      mensagemErro = "Preencha a URL da API a ser consumida.";
      GlobalScaffold.instance.showSnackBarErro(mensagemErro);
    }
  }
  
  _testarConexaoApi() async {
    
    mensagemErro = await configuracaoRepository.getConexaoApi(empresa, url);
      
  
    if (mensagemErro.contains("Status: Sucesso")){ 

      _gravarParam();        
      GlobalScaffold.instance.showSnackBarSucesso(mensagemErro);
      
    }
    else{      
      GlobalScaffold.instance.showSnackBarErro(mensagemErro);

    }
  }

  @action
  _preencherTextoParam({String controllerUrl, String controllerEmp}) async {

    Parametros parametros = Parametros();
    await parametros.buscarParametros(); 
    setURL(parametros.url_api);
    setEmpresa(parametros.codempresapadrao);

  }
  
  _gravarParam() async {

    Parametros parametros = Parametros();
    parametros.url_api = url;
    parametros.codempresapadrao = empresa;
    await parametros.gravarParametros();

  }
}

Code on the page

import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'configuracao_controller.dart';

class ConfiguracaoPage extends StatefulWidget {
  final String title;

  const ConfiguracaoPage({Key key, this.title = "Configuração"})
      : super(key: key);

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

class _ConfiguracaoPageState extends ModularState<ConfiguracaoPage, ConfiguracaoController> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Observer(builder: (_) {
          return Container(
            decoration: BoxDecoration(color: Color(0xfff0f3f4)),
            padding: EdgeInsets.all(16),
            child: Center(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.only(top: 50, bottom: 120),
                      child: Image.asset(
                        "Imagens/logo.png",
                        width: 200,
                        height: 150,
                      ),
                    ),
                    Padding(
                        padding: EdgeInsets.only(bottom: 8),
                        child: Observer(builder: (_) {
                          return TextFormField(
                            onChanged: controller.setURL,
                            initialValue: controller.url ?? "",
                            // controller: _controllerURL,
                            keyboardType: TextInputType.text,
                            style: TextStyle(fontSize: 20),
                            decoration: InputDecoration(
                                contentPadding:
                                    EdgeInsets.fromLTRB(32, 16, 32, 16),
                                hintText: "Url API",
                                filled: true,
                                fillColor: Colors.white,
                                border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(32))),
                          );
                        }),
                    ),
                    Observer(builder: (_) {
                    return TextFormField(
                      onChanged: controller.setEmpresa,
                      initialValue: controller.empresa,
                      // controller: _controllerEmpresa,
                      keyboardType: TextInputType.text,
                      style: TextStyle(fontSize: 20),
                      decoration: InputDecoration(
                          contentPadding: EdgeInsets.fromLTRB(32, 16, 32, 16),
                          hintText: "Empresa",
                          filled: true,
                          fillColor: Colors.white,
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(32))),
                    );
                    }),
                    Padding(
                      padding: EdgeInsets.only(top: 16, bottom: 10),
                      child: RaisedButton(
                        child: Text(
                          "Testar e Salvar",
                          style: TextStyle(color: Colors.white, fontSize: 20),
                        ),
                        color: Colors.pink,
                        padding: EdgeInsets.fromLTRB(32, 16, 32, 16),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(32)),
                        onPressed: () {
                          controller.validarCampos();
                        },
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
        }));
  }
}

I think there’s something I don’t understand about mobx, but I’m following several examples I’ve seen around the net.

1 answer

0


Try to create a reaction. I hope it helps you

ReactionDisposer disposer;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    ConfiguracaoController = Provider.of<ConfiguracaoController>(context);
    disposer = reaction(
      //Codigo de reação
    );
  }
  • 1

    Man, give him an improved answer... where he should fit this re-action? From what I’ve seen he’s using Modular, how he can make use of the Provider?

  • 1

    then from what I understand of mobx and what the didChangeDependencies Voce uses whenever it has a change in the state of the variables of the store class and then Voce creates a reaction. Reaction is inside @override void didChangeDependencies()

  • Thanks for the tip, I followed the example you gave me, a better study in the actions to work

Browser other questions tagged

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