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
356 views
in Technique[技术] by (71.8m points)

api - How can I fetch data from url by class name or id using Flutter?

As you see in the title of the question, I need to fetch data from URL by class name or id in Flutter. There is some data I haven't got its JSON data, and I need them to display on my app. I could fetch data using the code in the below, but I can't fetch any data by class name or id because I don't know what I need to use. Please help me

class _MyHomePageState extends State<MyHomePage> {
  String stringResponse;

  Future fetcData() async {
    http.Response response;
    response = await http.get("www.example.com"); //Consider that the URL has just a string such as "This is a string."
    if (response.statusCode == 200) {
      setState(() {
        stringResponse = response.body;
      });
    } else {
      
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    fetcData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Http request"),
      ),
      body: Center(
        child: Text(stringResponse.toString()),
      ),
    );
  }
}
question from:https://stackoverflow.com/questions/66061931/how-can-i-fetch-data-from-url-by-class-name-or-id-using-flutter

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

1 Reply

0 votes
by (71.8m points)

here is package http package.

here is a complete method to get a response.

     HttpClient client = new HttpClient()
          ..badCertificateCallback =
              ((X509Certificate cert, String host, int port) => true);


     return client.getUrl(Uri.parse(url)).then((HttpClientRequest request) {
      request.headers.set('content-type', 'application/json-patch+json');
      request.headers.set('accept', 'application/json');
      var response = request.close().timeout(new Duration(seconds: 5));
      return response;
    }).then((HttpClientResponse response) {
      var result = response.transform(utf8.decoder).join();
      return result;
    }).catchError((onError) {
      var result = onError.transform(utf8.decoder).join();
      return result;
    });
  

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

...