如何在flutter中解析API url

问题描述

我是 Flutter 的新手,想创建一个天气应用。调用 API 时出现错误。我创建了一个名为 fetchSearch() 的函数搜索位置。我已将 API URL 存储在字符串变量中,并且在调用 API 时,我使用函数 fetchSearch() 函数搜索解析为参数

error: The argument type 'String' can't be assigned to the parameter type 'Uri'.

颤动代码

    class _HomeState extends State<Home> {
  int temperature = 0;
  String location = "New York";
  int woeid = 2487956;

  String url = "https://www.Metaweather.com/api/location/search/?query=san";

  void fetchSearch(String input) async {
    var searchResult = await http.get(url+input); //here's the error
    var result = json.decode(searchResult.body)[0];

    setState(() {
      location = result["title"];
      woeid = result["woeid"];
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Container(
        decoration: Boxdecoration(
          image: decorationImage(
              image: Assetimage('images/clear.png'),fit: BoxFit.cover),),child: Scaffold(
          backgroundColor: Colors.transparent,body: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,crossAxisAlignment: CrossAxisAlignment.center,children: [
              Column(
                children: [
                  Center(
                    child: Text(
                      temperature.toString() + " C",style: TextStyle(color: Colors.white,fontSize: 60.0),Center(
                    child: Text(
                      location,fontSize: 40.0),],Column(
                children: [
                  Container(
                    width: 300,child: TextField(
                      style: TextStyle(color: Colors.white,fontSize: 25.0),decoration: Inputdecoration(
                          hintText: "Search location",hintStyle:
                              TextStyle(color: Colors.white,fontSize: 18.0),prefixIcon: Icon(Icons.search)),)
                ],);
  }
}

解决方法

试试这个

var uri = Uri.parse('https://www.metaweather.com/api/location/search/?query=san');