简体   繁体   中英

Flutter // click button to execute two function using async and wait on function onPressed and get data from api

try to put some value on local variable on TextField and onPressed to get one variable on local and second variable as given on TextField and the same time click the onPressed to working two functions one is doSomething another one is fetchBalance function. The first function doSomthig is working properly but the fetchBalance function response body is printed successfully but the inside condition is not executed but code is not given any error on the program. now, i stuck on this please help me.

This is our variables

var _addressControler= TextEditingController();
  var url1='This is default variable ';
  var url2='noAddress entered';

First function

doSomething(){
    setState(() {
      if(_addressControler.text == _addressControler.text){
        url2 = _addressControler.text.toString();
      }else{
        url2=url2;
        print("$url2");
      }
      print("$url2");
    });
  }

This is local variable for balance

 late Future<Balance> futureBalance;
  final _formKey = GlobalKey<FormState>();

  @override
   void initState() {
   super.initState();
  futureBalance = fetchBalance();
  }

 Future<Balance> fetchBalance() async {
    print("$url1");
    print("$url2");
    var finalAddress=url1+url2;
    print("$finalAddress");
    final response =
    await http.get(Uri.parse(finalAddress));

    print(response.body);

    if (response.statusCode == 200) {
      return Balance.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Failed to load album');
    }
  }

 @override Widget build(BuildContext context) {

return Scaffold(
  backgroundColor: Colors.amberAccent,
  appBar: AppBar(
    title: const Text('Retrieve Text Input'),
  ),
  body: Padding(
    key: _formKey,
    padding: const EdgeInsets.all(16.0),

    child: Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(10.0),
          child: TextField(
            controller: _addressControler,
            decoration: InputDecoration(labelText: 'Enter the address...',
            labelStyle: TextStyle(color: Colors.blue),border: new OutlineInputBorder(
                borderSide:new BorderSide(color: Colors.black)),),
          ),
        ),

        Padding(
          padding: const EdgeInsets.symmetric(vertical: 16.0),
          child: ElevatedButton(
            onPressed:() async{
              doSomething();
              await fetchBalance();
            },
            child: const Text('Submit'),
      throw Exception('Failed to load album');
    }
  }

this is our ui base

@override
  Widget build(BuildContext context) {
    
    return Scaffold(
      backgroundColor: Colors.amberAccent,
      appBar: AppBar(
        title: const Text('Retrieve Text Input'),
      ),
      body: Padding(
        key: _formKey,
        padding: const EdgeInsets.all(16.0),

        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: TextField(
                controller: _addressControler,
                decoration: InputDecoration(labelText: 'Enter the address...',
                labelStyle: TextStyle(color: Colors.blue),border: new OutlineInputBorder(
                    borderSide:new BorderSide(color: Colors.black)),),
              ),
            ),

            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: ElevatedButton(
                onPressed:() async{
                  doSomething();
                  await fetchBalance();
                },
                child: const Text('Submit'),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: Text("$url2"),
            ),
            Container(
              child: FutureBuilder<Balance>(
              future: futureBalance,
               builder: (context, snapshot) {
               if (snapshot.hasData) {
               print(snapshot.data!.height);
              print(snapshot.data!.result[0].amount);
               var x = (snapshot.data!.result[0].amount);
               var y =int.parse(x);
                assert(y is int);
                  ),
                ],
              );
                 } else if (snapshot.hasError) {
                 return Text("${snapshot.error}");
                 }
                 // By default, show a loading spinner.
                 return CircularProgressIndicator();
               },
            ),

            ),
          ],
        ),
      )
    );
  }
 
}
            print(z);
               return
               Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('${z.toString()}',style: TextStyle(fontSize: 20,),),
                      ],
                    ),
                  ),
                ],
              );
                 } else if (snapshot.hasError) {
                 return Text("${snapshot.error}");
                 }
                 // By default, show a loading spinner.
                 return CircularProgressIndicator();
               },
            ),

            ),
          ],var _addressControler= TextEditingController();
 
        ),
      )
    );
  }
 
}

you don't need to url2 variable just send _addressControler.text in fetchBalance()

 Future<Balance> fetchBalance() async {  
    final response =
    await http.get(Uri.parse(url1 +_adressController.text));
    if (response.statusCode == 200) {
      return Balance.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Failed to load album');
    }
  }

it's working...

child: ElevatedButton(
                        onPressed: ()  {
                          setState(() {
                            fetchBalance();
                          });
                          fetchBalance();
                        },
                        child: const Text('Submit'),
                      ),
                    ),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM