Я сделал приложение с Flutter, которое работает для Android и iOS, а не для Интернета. Я могу запустить приложение и перемещаться по нему, но не могу войти в систему, ответ сервера положительный, но когда я нажимаю на кнопку, она не перенаправляется на следующую страницу (помните, что вход в систему выполняется). Работаем над этим в течение нескольких недель, но не может решить. < /P>
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gianni_gomme/Dashboard.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart'; // Importa
shared_preferences
import 'Bottomnavigationbar.dart';
import 'SignUp.dart';
class Login extends StatefulWidget {
const Login({super.key});
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State {
final TextEditingController targaController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
Future login(String targa, String password) async {
final url = 'https://www.giannigommegestionale.it/Login.php';
try {
final response = await http.post(
Uri.parse(url),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: {'targa': targa, 'password': password},
);
if (response.statusCode == 200) {
var setCookie = response.headers['set-cookie'];
if (setCookie != null) {
var sessionId = RegExp(r'PHPSESSID=.
([^;]+);').firstMatch(setCookie)?.group(1);
if (sessionId != null) {
await setSessionId(sessionId); // Salva il sessionId usando
shared_preferences
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Dashboard()),
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Accesso riuscito!')),
);
}
}
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Errore: Credenziali non valide o utente non ancora
confermato')),
);
}
} catch (error) {
print('Errore nella richiesta: $error');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Connessione al server fallita, riprovare più tardi')),
);
}
}
// Funzione per salvare il sessionId usando shared_preferences
Future setSessionId(String sessionId) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('PHPSESSID', sessionId);
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: true, // Evita l'overflow quando si apre la tastiera
body: SingleChildScrollView(
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
color: Colors.white,
child: Column(
children: [
// Sezione del logo
Expanded(
flex: 2,
child: Center(
child: Image.asset(
'images/logogianni.jpg',
width: 300,
height: 300,
),
),
),
// Sezione del contenitore
Expanded(
flex: 3,
child: Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
spreadRadius: 5,
blurRadius: 10,
offset: Offset(0, -3),
),
],
),
padding: const EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Theme(
data: Theme.of(context).copyWith(
inputDecorationTheme: InputDecorationTheme(
labelStyle: TextStyle(
color: Colors.grey, // Colore del testo in stato normale
),
floatingLabelStyle: TextStyle(
color: Color(0XFF910000), // Colore del testo in stato
),
),
),
child: TextField(
controller: targaController,
decoration: InputDecoration(
labelText: 'Targa',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(
color: Color(0XFF910000), // Colore del bordo quando è
width: 2.0,
),
),
prefixIcon: Icon(Icons.person, color: Color(0XFF910000)),
),
),
),
SizedBox(height: 20),
Theme(
data: Theme.of(context).copyWith(
inputDecorationTheme: InputDecorationTheme(
labelStyle: TextStyle(
color: Colors.grey, // Colore del testo in stato normale
),
floatingLabelStyle: TextStyle(
color: Color(0XFF910000), // Colore del testo in stato
),
),
),
child: TextField(
obscureText: true,
controller: passwordController,
decoration: InputDecoration(
labelText: 'Password',`enter code here`
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(
color: Color(0XFF910000), // Colore del bordo quando è
width: 2.0,
),
),
prefixIcon: Icon(Icons.lock, color: Color(0XFF910000)),
),
),
),
SizedBox(height: 30),
ElevatedButton(
onPressed: () async {
await login(targaController.text, passwordController.text);
},
child: Text('Accedi', style: TextStyle(fontWeight:
FontWeight.bold, fontSize: 20)),
style: ElevatedButton.styleFrom(
backgroundColor: Color(0XFF910000),
foregroundColor: Colors.white,
padding: EdgeInsets.symmetric(vertical: 15.0, horizontal:
70.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
elevation: 5,
),
),
SizedBox(height: 20),
TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SignUp()),
);
},
child: Text('Non hai un account? Registrati', style:
TextStyle(color: Color(0XFF910000), fontSize: 16)),
),
],
),
),
),
],
),
),
),
);
}
}
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Credentials: True");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Ricevi i dati dal form
$targa = $_POST['targa'];
$password = $_POST['password'];
}
// Debug: stampa i dati ricevuti
// Verifica che i dati non siano vuoti
if(empty($targa) || empty($password)) {
die("targa o password non possono essere vuoti");
}
// Connessione al DATABASE DI GIANNIGOMME GESTIONALE
$servername = "myserv";
$db_username = "myuse";
$db_password = "mypw";
$dbname = "myname";
// Crea connessione al database
$conn = new mysqli($servername, $db_username, $db_password, $dbname);
// Controlla la connessione
if ($conn->connect_error) {
die("Connessione Fallita: " . $conn->connect_error);
}
echo "Connessione riuscita";
// Crittografia della password
$hashed_password = md5($password);
// Esegui la query per cercare utente nel database
$sql = "SELECT ut_log, ut_pwd, ut_lev_id, ut_nick, ut_attivo, ut_cognome FROM
gs_utenti WHERE ut_log = '$targa'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// recupera i dati dell'utente
$row = $result->fetch_assoc();
// Verifica se l'hash corrisponde a quello nel database
if ($hashed_password == $row['ut_pwd'] && $row['ut_attivo'] == 'si' ) {
http_response_code(200);
echo "Login riuscito! Benvenuto ";
$_SESSION["sesslog"] = $row["ut_log"];
$_SESSION["sesslevel"] = $row["ut_lev_id"];
$_SESSION["sessnick"] = $row["ut_nick"];
$_SESSION["sessname"] = $row["ut_cognome"];
exit();
} else {
http_response_code(401);
echo "Password errata o utente non ancora confermato";
}
} else {
http_response_code(404);
echo "Utente non trovato.";
}
// Chiude la connessione
$conn->close();
Подробнее здесь: https://stackoverflow.com/questions/795 ... on-android
Flutter - Визуальная навигация не работает над Flutter Web, она работает на Android ⇐ Php
Кемеровские программисты php общаются здесь
1743470967
Anonymous
Я сделал приложение с Flutter, которое работает для Android и iOS, а не для Интернета. Я могу запустить приложение и перемещаться по нему, но не могу войти в систему, ответ сервера положительный, но когда я нажимаю на кнопку, она не перенаправляется на следующую страницу (помните, что вход в систему выполняется). Работаем над этим в течение нескольких недель, но не может решить. < /P>
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gianni_gomme/Dashboard.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart'; // Importa
shared_preferences
import 'Bottomnavigationbar.dart';
import 'SignUp.dart';
class Login extends StatefulWidget {
const Login({super.key});
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State {
final TextEditingController targaController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
Future login(String targa, String password) async {
final url = 'https://www.giannigommegestionale.it/Login.php';
try {
final response = await http.post(
Uri.parse(url),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: {'targa': targa, 'password': password},
);
if (response.statusCode == 200) {
var setCookie = response.headers['set-cookie'];
if (setCookie != null) {
var sessionId = RegExp(r'PHPSESSID=.
([^;]+);').firstMatch(setCookie)?.group(1);
if (sessionId != null) {
await setSessionId(sessionId); // Salva il sessionId usando
shared_preferences
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Dashboard()),
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Accesso riuscito!')),
);
}
}
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Errore: Credenziali non valide o utente non ancora
confermato')),
);
}
} catch (error) {
print('Errore nella richiesta: $error');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Connessione al server fallita, riprovare più tardi')),
);
}
}
// Funzione per salvare il sessionId usando shared_preferences
Future setSessionId(String sessionId) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('PHPSESSID', sessionId);
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: true, // Evita l'overflow quando si apre la tastiera
body: SingleChildScrollView(
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
color: Colors.white,
child: Column(
children: [
// Sezione del logo
Expanded(
flex: 2,
child: Center(
child: Image.asset(
'images/logogianni.jpg',
width: 300,
height: 300,
),
),
),
// Sezione del contenitore
Expanded(
flex: 3,
child: Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
spreadRadius: 5,
blurRadius: 10,
offset: Offset(0, -3),
),
],
),
padding: const EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Theme(
data: Theme.of(context).copyWith(
inputDecorationTheme: InputDecorationTheme(
labelStyle: TextStyle(
color: Colors.grey, // Colore del testo in stato normale
),
floatingLabelStyle: TextStyle(
color: Color(0XFF910000), // Colore del testo in stato
),
),
),
child: TextField(
controller: targaController,
decoration: InputDecoration(
labelText: 'Targa',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(
color: Color(0XFF910000), // Colore del bordo quando è
width: 2.0,
),
),
prefixIcon: Icon(Icons.person, color: Color(0XFF910000)),
),
),
),
SizedBox(height: 20),
Theme(
data: Theme.of(context).copyWith(
inputDecorationTheme: InputDecorationTheme(
labelStyle: TextStyle(
color: Colors.grey, // Colore del testo in stato normale
),
floatingLabelStyle: TextStyle(
color: Color(0XFF910000), // Colore del testo in stato
),
),
),
child: TextField(
obscureText: true,
controller: passwordController,
decoration: InputDecoration(
labelText: 'Password',`enter code here`
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(
color: Color(0XFF910000), // Colore del bordo quando è
width: 2.0,
),
),
prefixIcon: Icon(Icons.lock, color: Color(0XFF910000)),
),
),
),
SizedBox(height: 30),
ElevatedButton(
onPressed: () async {
await login(targaController.text, passwordController.text);
},
child: Text('Accedi', style: TextStyle(fontWeight:
FontWeight.bold, fontSize: 20)),
style: ElevatedButton.styleFrom(
backgroundColor: Color(0XFF910000),
foregroundColor: Colors.white,
padding: EdgeInsets.symmetric(vertical: 15.0, horizontal:
70.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
elevation: 5,
),
),
SizedBox(height: 20),
TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SignUp()),
);
},
child: Text('Non hai un account? Registrati', style:
TextStyle(color: Color(0XFF910000), fontSize: 16)),
),
],
),
),
),
],
),
),
),
);
}
}
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Credentials: True");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Ricevi i dati dal form
$targa = $_POST['targa'];
$password = $_POST['password'];
}
// Debug: stampa i dati ricevuti
// Verifica che i dati non siano vuoti
if(empty($targa) || empty($password)) {
die("targa o password non possono essere vuoti");
}
// Connessione al DATABASE DI GIANNIGOMME GESTIONALE
$servername = "myserv";
$db_username = "myuse";
$db_password = "mypw";
$dbname = "myname";
// Crea connessione al database
$conn = new mysqli($servername, $db_username, $db_password, $dbname);
// Controlla la connessione
if ($conn->connect_error) {
die("Connessione Fallita: " . $conn->connect_error);
}
echo "Connessione riuscita";
// Crittografia della password
$hashed_password = md5($password);
// Esegui la query per cercare utente nel database
$sql = "SELECT ut_log, ut_pwd, ut_lev_id, ut_nick, ut_attivo, ut_cognome FROM
gs_utenti WHERE ut_log = '$targa'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// recupera i dati dell'utente
$row = $result->fetch_assoc();
// Verifica se l'hash corrisponde a quello nel database
if ($hashed_password == $row['ut_pwd'] && $row['ut_attivo'] == 'si' ) {
http_response_code(200);
echo "Login riuscito! Benvenuto ";
$_SESSION["sesslog"] = $row["ut_log"];
$_SESSION["sesslevel"] = $row["ut_lev_id"];
$_SESSION["sessnick"] = $row["ut_nick"];
$_SESSION["sessname"] = $row["ut_cognome"];
exit();
} else {
http_response_code(401);
echo "Password errata o utente non ancora confermato";
}
} else {
http_response_code(404);
echo "Utente non trovato.";
}
// Chiude la connessione
$conn->close();
Подробнее здесь: [url]https://stackoverflow.com/questions/79547557/flutter-visual-navigation-not-working-on-flutter-web-it-works-on-android[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия