I have a widget that gets title from a webpage which is :
Widget ref_box(BuildContext context,String reference){
Future <String> scrap_title(url_received) 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');
var elements;
if (resp.statusCode ==200){
dom.Document doc = parser.parse(resp.body);
elements = doc.querySelector('title');
// final linkElemnt=doc.getElementsByClassName('entry-title');
//var html = dom.Document.html(resp.body).head!.text.trim();
}
return Future.value(elements!.text);
}
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(padding: EdgeInsets.symmetric(vertical: 3)),
FutureBuilder<String>(
future: scrap_title(reference),
builder: (BuildContext context, AsyncSnapshot snapshot){
if (snapshot.hasData == false) {
return CircularProgressIndicator();
}
else
return Text(snapshot.data);
},
),
//Text(ref_title),
Padding(padding: EdgeInsets.symmetric(vertical: 3))
],
);
}
I called this ref_box two times, one in stateful class and one in dialog.
The dialog-calling code is as following :
void Function()? _showPost_Dialog(String content, String writer, int like,int shared,String ref) {
showDialog(
context: context,
builder: (context) {
String lls = like.toString();
// return object of type Dialog
return
Dialog(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(10.0)), //this right here
child:
Container(height: MediaQuery.of(context).size.height*0.7,
padding: EdgeInsets.symmetric(horizontal: 10),
child:GestureDetector(onTap: (){
if(ref==' ' ||ref=='') {
print('Reference 없음');
return;
}
_showWeb(writer, ref);
},
child: ref_box(context, ref),
),
);
This _showPost_Dialog()
is called when a GestureDetector is pressed.
I confirmed that ref_box()
called at a class worked well however one called at _showPost_Dialog()
did not.
The print
code told me that await http.get(url);
does not work when it is called in _showPost_Dialog()
.
Why does this happen ? What should I do to make this work even in dialog?
CodePudding user response:
This function takes a builder which typically builds a Dialog widget. Content below the dialog is dimmed with a ModalBarrier. The widget returned by the builder does not share a context with the location that showDialog is originally called from. Use a StatefulBuilder or a custom StatefulWidget if the dialog needs to update dynamically.
So the easiest solution (and better anyway, even if it had worked) would be to take your ref_box
method and make a proper StatefulWidget from it. Then you can store your Future in your state, too, instead of calling the producing method (potentially multiple times) in your build method.