I am unable to get the data from below API response.Is there something called Observable pattern which I can use here? Please guide
API response is in this format:
[{"userId":160,"userName":"Reshma","userMobile":"8080808080","userEmail":"[email protected]","password":"$2a$10$BgzWbEGGjw4mloo92merguOSrFe91ir/J9bUDO2qv.ZgTmdeum4.y","userPassword":"1221","role":"ADMIN","userCity":"Pune"}]
Please refer below code:
LoginController.dart
static Future<List<UserLogin>> login(String email, String password) async {
print(email);
final response = await http.get(Uri.parse(
'http://192.168.0.111:8081/AtdochubJ-3/user/login?useremail=$email&userpassword=$password'));
;
print(email);
if (response.statusCode == 200) {
print('response $response');
final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
return parsed.map<UserLogin>((json) => UserLogin.fromJson(json)).toList();
} else {
throw Exception('Failed to load Document');
}
}
LoginPage.dart
import 'dart:async';
import 'package:AtDocHUB/Model/User.dart';
import 'package:AtDocHUB/View/AppointmentPageFE.dart';
import 'package:AtDocHUB/View/homePageAdmin.dart';
import 'package:flutter/material.dart';
import 'package:AtDocHUB/Controller/LoginController.dart';
import 'package:fluttertoast/fluttertoast.dart';
class LoginPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
const appTitle = 'User Login';
return MaterialApp(
debugShowCheckedModeBanner: false,
title: appTitle,
home: Scaffold(
// appBar: AppBar(
// title: const Text(appTitle),
// ),
body: MyCustomForm(),
),
);
}
}
// Create a Form widget.
class MyCustomForm extends StatefulWidget {
@override
MyCustomFormState createState() {
return MyCustomFormState();
}
}
// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
// Create a global key that uniquely identifies the Form widget
// and allows validation of the form.
//
// Note: This is a GlobalKey<FormState>,
// not a GlobalKey<MyCustomFormState>.
late Future<UserLogin> futureLogin;
late Future _futureAuth;
final _formKey = GlobalKey<FormState>();
TextStyle style = const TextStyle(
fontFamily: 'Montserrat',
fontSize: 20.0,
);
List<UserLogin> logs = [];
List<UserLogin> userRole = [];
String email = '';
String pass = '';
TextEditingController emailController = TextEditingController();
TextEditingController pwController = TextEditingController();
@override
Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
return SingleChildScrollView(
child: Form(
key: _formKey,
child: Center(
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 130,
),
Center(
child: SizedBox(
height: 155,
child: Image.asset(
"assets/AtDocHublogo.png",
fit: BoxFit.contain,
)),
),
SizedBox(
height: 45,
),
TextFormField(
controller: emailController,
style: style,
decoration: InputDecoration(
contentPadding: const EdgeInsets.fromLTRB(
20.0, 15.0, 20.0, 15.0),
hintText: "Email",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(32.0))),
),
SizedBox(height: 25.0),
TextFormField(
controller: pwController,
style: style,
decoration: InputDecoration(
contentPadding: const EdgeInsets.fromLTRB(
20.0, 15.0, 20.0, 15.0),
hintText: "Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(32.0))),
),
SizedBox(height: 35.0),
MaterialButton(
height: 55,
child: Text("Login",
textAlign: TextAlign.center,
style: style.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold)),
minWidth: MediaQuery.of(context).size.width,
elevation: 5.0,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.all(Radius.circular(30.0))),
color: Color.fromARGB(255, 3, 89, 168),
onPressed: () {
final String email = emailController.text;
final String pass = pwController.text;
LoginController.login(email, pass);
List<UserLogin> res =
LoginController.login(email, pass)
as List<UserLogin>;
print(res[0].role);
print(res[0].role);
if (res != []) {
if (res[0].role == 'ADMIN') {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => homePageAdmin()));
} else {
Fluttertoast.showToast(
msg: "User Doesn't Exists",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor:
Color.fromARGB(255, 3, 87, 156),
textColor: Colors.white,
fontSize: 12.0);
}
}
} )
])))),
);
}}
CodePudding user response:
In your LoginController.dart
, do this:
import 'dart:convert';
then
if (response.statusCode == 200) {
print('response $response');
final parsed = jsonDecode(response.body) as List;
return parsed.map((e) => UserLogin.fromJson(e)).toList();
} else {
throw Exception('Failed to load Document');
}
your api response is a List of map but you were casting it to map.
CodePudding user response:
Assuming LoginController.login
works, wait for a response like this:
onPressed: () async {
final String email = emailController.text;
final String pass = pwController.text;
List<UserLogin> res = await LoginController.login(email, pass);
print(res[0].role);
}
Read more about Working with futures: async and await.