簡體   English   中英

如何在 flutter 中解析 API url

[英]How to parse API url in flutter

我是 flutter 的新手,想創建一個天氣應用程序。 調用API時出現錯誤。 我創建了一個名為 fetchSearch() 的 function 來搜索位置。 I have stored the API URL in a string variable and when calling the API, I parse the search as a parameter using the function fetchSearch() function

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

Flutter 代碼。

    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,
                      style: TextStyle(color: Colors.white, 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');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM