Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

flutter - Using initState to get values from functions and insert into variable before Build

I have two functions that I'm attempting to get the values from, and store into variables in the main_page so I can use inside the build widget. I'm working with firebase realtime database.
The functions I have are:

Future<List> receive_button(String button) async{
    List<String> lst = new List<String>(2);

    final FirebaseUser user = await _auth.currentUser();
    var snapshot = await databaseReference.child(user.uid+"/buttons/"+button+"/icon").once();
    String result = snapshot.value;

    var snapshot1 = await databaseReference.child(user.uid+"/buttons/"+button+"/nome").once();
    String result1 = snapshot1.value;
    
    lst[0] = result;
    lst[1] = result1;

    print(lst);
    return lst;
  }

  Future<int>  receive_quantity() async{
    final FirebaseUser user = await _auth.currentUser();
    var snapshot = await databaseReference.child(user.uid+"/buttons/quantity").once();
    var result = snapshot.value;
    print(result);
    return result;
  }

This is how I'm attempting to store the data inside the variables in the home_page:

class _HomeState extends State<Home> {

  int quantity = 0;
  List<String> lst = new List<String>(2);

  final AuthService _auth = AuthService();
  
  @override
  void initState() {
    super.initState();
    _auth.receive_quantity().then((value) => quantity = value);
    _auth.receive_button("button1").then((value) => lst = value);
  }

But whenever I attempt to print the values inside the Widget build, I get the following:

flutter: 0
flutter: [null, null]

In my database this flutter: 0, the real value is 2.
And this flutter: [null, null]has ["add", "Chocolate"]
I have tested the function itself and it gives me the right data, I'm having problems storing them only.

question from:https://stackoverflow.com/questions/65836223/using-initstate-to-get-values-from-functions-and-insert-into-variable-before-bui

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try this, as i know you cannot use await in overriden method initState(), so this is what i usually do and it works fine

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

void asyncInit() async {
   quantity = await _auth.receive_quantity();
   lst = await _auth.receive_button("button1");
   setState(() {});
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...