【发布时间】:2020-09-16 13:36:16
【问题描述】:
我是 Flutter 的新手,编写了以下 Flutter 程序来获取客户端 IP 地址和位置。我正在呼叫“http://ip-api.com/json”以获取 IP 地址和位置信息。该程序通过使用设备“chrome”和“web server”可以正常工作,我可以在页面上打印客户端的位置。
.
当我部署到 github 网页或 firebase 托管时,程序永远显示“加载循环”。程序部署到github web服务器(或其他web服务器)后,似乎无法获取ip地址。
一旦我将程序部署到 Github html 页面或 firebase 托管,我发现该程序抛出“XMLHTTPRequest 错误”。它在本地 Web 服务器或 chrome 上运行良好。对此有何建议?非常感谢。
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class IP_info{
final String IP;
final String city;
final String ZIP;
final String st_code;
final String state_name;
final String country_code;
final String country_name;
IP_info({this.IP, this.city, this.st_code,this.ZIP,
this.state_name,this.country_code,this.country_name});
factory IP_info.fromJson(Map<String, dynamic> json){
return IP_info(
IP:json['query'],
ZIP:json['zip'],
city:json['city'],
country_code:json['countryCode'],
st_code:json['region'],
country_name:json['country_name'],
state_name:json['regionName'],
);
}
}
void main() {
runApp(MaterialApp(
title: 'Covid 19 cases near you',
home: MyApp()
),
);
}
class MyApp extends StatefulWidget{
@override
State<StatefulWidget> createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
bool _isLoading = false;
IP_info ip_info;
@override
void initState() {
_isLoading=true;
_getPublicIP();
}
_getPublicIP() async {
try {
const url = 'http://ip-api.com/json';
final response = await http.get(url);
if (response.statusCode == 200) {
ip_info = IP_info.fromJson(json.decode(response.body));
print(ip_info.toString());
setState(() {
_isLoading = false;
});
}
else {
// The request failed with a non-200 code
print(response.statusCode);
print(response.body);
}
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Testing IP address'), ),
body: Container(
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.white,
),
child: _isLoading? Center(
child: Column(children: [
CircularProgressIndicator(),
SizedBox(height: 10,),
Text("Loading your location infomation ...", style: TextStyle(color: Colors.blueAccent),),
]
)
)
: new Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center ,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget> [
Text('You are in ${ip_info.city} ${ip_info.state_name} ',
style: TextStyle(
fontWeight: FontWeight.bold,),
),
],
),
)
);
}
【问题讨论】:
标签: google-chrome flutter web dart server