I'm pretty new to flutter, and wrote the following flutter program to get the client IP address and location. I'm calling "http://ip-api.com/json" for IP address and location information. The program works okay by using device "chrome", I can print client's IP address on the title bar.
. When I switch to device "web server", and the program print nothing on the title bar, and it just show a blank page. I have been struggle on this for a week now. Is this because that flutter is still in beta version for web support? Your help is highly appreciated.
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: 'This is a test',
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));
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 your IP Address ${ip_info.IP}'),),
);
}
}
Aucun commentaire:
Enregistrer un commentaire