Home > database >  await http.get(url) does not work even in StatefulWidget
await http.get(url) does not work even in StatefulWidget

Time:08-22

2 days ago, I asked the solution of my problem in this post and got answer to make another statefulwidget and use http codes. So my code became :

class _post_openState extends State<post_open> {
  void initState() {
    super.initState();
    // Enable virtual display.
    if (Platform.isAndroid) WebView.platform = AndroidWebView();
//      else if(Platform.isIOS)WebView.platform =
  }
  @override
  Future <String> _scrap_title(url_received) async
  {
    var elements;
    url_received = url_received.split(' ')[-1];
    if (url_received.split(':')[0] !='https')
      url_received = 'https://'   url_received;
    print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%');
    print(url_received);
    bool suc = false;
   // Future.delayed(Duration.zero,() async {
      print('response init');
      if (url_received == '' || url_received == ' ') return 'No reference';
      final url = Uri.parse(url_received);
      print('response parsed');
      final resp = await http.get(url);
      print('response on');
      print(resp.statusCode);
      if (resp.statusCode == 200) {
        dom.Document doc = parser.parse(resp.body);
        elements = doc.querySelector('title');
        suc = true;
      }
    //}
    //);

      return Future.value(elements!.text);

  }
  Widget build(BuildContext context){
    String reference = widget.data_received[5];
    bool leftright = widget.data_received[0];
    String content = widget.data_received[1];
    String writer = widget.data_received[2];
    int like = widget.data_received[3];
    int shared = widget.data_received[4];
    print(widget.data_received);
    print('**************************************');
    void Function()? _showWeb(String title, String url)
    {
      showDialog(
          context: context,
          builder: (context) {
            return Container(
                height: MediaQuery.of(context).size.height*0.9,
                width: MediaQuery.of(context).size.width*0.95,
                padding: EdgeInsets.symmetric(horizontal: 3),
//

                child:
                Dialog(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.0)

                    ), //this right here
                    child:
                    Column(
                      mainAxisAlignment: MainAxisAlignment.start,

                      children: <Widget>[
                        Padding(padding: EdgeInsets.symmetric(vertical: 10)),
                        Text(title),

                        Padding(padding: EdgeInsets.symmetric(vertical: 3)),
                        Container(height:2,color:Colors.brown),
                        Container(
                          height: MediaQuery.of(context).size.height*0.7,
                          width: MediaQuery.of(context).size.width*0.9,

                          padding: EdgeInsets.symmetric(horizontal: 5),
                          child:
                          Expanded(
                            child:WebView(
                              initialUrl: url,
                              javascriptMode: JavascriptMode.unrestricted,
                            ),

                          ),


                        ),
                        Container(height:2,color:Colors.brown),
                        Padding(padding: EdgeInsets.symmetric(vertical: 3)),

                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            TextButton.icon(onPressed: (){
                              setState(){

                              };
                            }, icon:Icon(Icons.thumb_up_alt_outlined),label: Text('like'),style: TextButton.styleFrom(primary: Colors.brown)),
                            GestureDetector(
                              onTap: (){
                                Navigator.pop(context);
                              },
                              child:Container
                                (

                                  width: MediaQuery.of(context).size.width*0.4,
                                  height: 30,

                                  color:Colors.amber,
                                  child:Text('Back',style: TextStyle(fontSize:20,color: Colors.white),
                                    textAlign: TextAlign.center,)
                              ),
                            ),
                            TextButton(onPressed: (){
                              setState(){

                              };
                            }, child: Icon(Icons.share),style: TextButton.styleFrom(primary: Colors.brown)),


                          ],
                        ),
                      ],
                    )

                )

            );

          });
    }

    return
      Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: AppBar(
            backgroundColor: Colors.white,
            toolbarHeight: 1.0,
          ),

          body:
          Column(

              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Align(
                  alignment: Alignment.topLeft,
                  child: SizedBox(
                    height: 40,
                    width: 40,
                    child:
                    TextButton(onPressed: () {
                      Navigator.pop(context);
                    },
                        style: TextButton.styleFrom(primary: Colors.brown,),
                        child: Icon(Icons.arrow_back)
                    ),
                  ),
                ),
                Padding(padding: EdgeInsets.symmetric(vertical: 5)),
          FutureBuilder<String>(
          future: _scrap_title(reference),
          builder: (BuildContext context, AsyncSnapshot snapshot){
            print('snapshot status'  snapshot.hasData.toString());
            if (snapshot.hasData == false) {
              return CircularProgressIndicator();
            }
            else
              return GestureDetector(onTap: (){
                _showWeb(writer, reference);
              },
                child:Text(snapshot.data,style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),),
              );

          }),

                Padding(padding: EdgeInsets.symmetric(vertical: 5)),

                Container(
                  height:1,
                  color: Colors.brown,
                ),
                Padding(padding: EdgeInsets.symmetric(vertical: 5)),
                Text(content,style: TextStyle(color:Colors.black87,fontSize: 15)),

              ]

          )
      );
  }

}

But strangely, testing by print told me that this class does not even call _scrap_title.

I am having confusion of understanding lifecysle of widget/future/async and so on. Why do I keep failing to scrap html title of a web ? PLEASE somebody give me solution. Thank you so much.

CodePudding user response:

Can you try replacing @override

 ///@override remove it 
  Future <String> _scrap_title(url_received) async
  {....}

 @override //add it  here
 Widget build(BuildContext context){

also better practice put variable outside the build method, you can use initState or use late

  late String reference = widget.data_received[5];
  late   bool leftright = widget.data_received[0];
  ....
  
 @override
  Widget build(BuildContext context){
 

More about StatefulWidget

  • Related