我是 dart/flutter 的新手。
我编写了一段代码,它从输入字段中获取值并替换为 url 中的链接以检查授权并返回以下响应:
"result": {
"Result": 0,
"RequiredInfo": 0,
"Custom": {},
"Name": "1",
"UserId": 4,
"AuthenticationType": "",
"Role": 1,
"Claims": [
{
"type": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
"value": "1"
}
]
},
"httpStatusCode": 200
}
我在按钮方法中写了代码,
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:ultra/widgets/data/login_user.dart';
final loginUserText = TextEditingController();
final passwordUserText = TextEditingController();
const String login = '1';
const String pass = '1';
final String basicAuth = 'Basic ' + base64Encode(utf8.encode('$login:$pass'));
class InputFields extends StatefulWidget {
const InputFields({
Key? key,
}) : super(key: key);
@override
InputFieldsState createState() => InputFieldsState();
}
class InputFieldsState extends State<InputFields> {
@override
Widget build(BuildContext context) {
return Container(
width: 350,
child: Column(
children: [
LoginFieldWidget(loginUserText: loginUserText),
SizedBox(
height: 15,
),
PasswordFieldWidget(passwordUserText: passwordUserText),
ButtonWidget(),
],
),
);
}
}
///////////////////////////// MAIN BUTTON ////////////////////////////////////
class ButtonWidget extends StatefulWidget {
const ButtonWidget({
Key? key,
}) : super(key: key);
@override
_ButtonWidgetState createState() => _ButtonWidgetState();
}
class _ButtonWidgetState extends State<ButtonWidget> {
@override
Widget build(BuildContext context) {
//////////////// SHOW DIALOG ERROR WINDOW /////////////////////////////////
Future<void> _showMyDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
title: const Text(
'Ошибка',
style: TextStyle(color: Colors.red),
),
content: SingleChildScrollView(
child: ListBody(
children: const <Widget>[
Text(
'Вы ввели неправильный логин или пароль.',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
),
SizedBox(
height: 15,
),
Text(''),
],
),
),
actions: <Widget>[
TextButton(
child: const Text(
'OK',
style: TextStyle(fontSize: 28, color: Colors.red),
),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
//////////////////////////// AUTH FUNCTION ////////////////////////////////
Future<dynamic> fetchData() async {
final loginUser = loginUserText.text;
final passUser = passwordUserText.text;
final url = Uri.parse(
'http://xx.xxx.xxx.xxx/api/users/$loginUser/$passUser/valid');
final response = await http
.get(url, headers: <String, String>{'authorization': basicAuth});
Map<String, dynamic> parsed = json.decode(response.body);
final user = User.fromJson(parsed);
if (user.httpStatusCode == 200 && user.result!.result == 0) {
Navigator.of(context).pushNamed('/main_screen');
} else {
_showMyDialog();
}
}
/////////////////////// ENTER BUTTON ////////////////////////////////////
return Container(
margin: EdgeInsets.only(top: 15),
width: 250,
height: 50,
child: ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
side: BorderSide(color: Colors.red),
),
),
backgroundColor: MaterialStateProperty.all(Colors.red),
),
onPressed: () {
setState(() {
fetchData();
});
},
child: Text(
'ВОЙТИ',
style: TextStyle(fontSize: 20),
),
),
);
}
}
////////////////////////// PASSWORD FIELD //////////////////////////////////
class PasswordFieldWidget extends StatelessWidget {
const PasswordFieldWidget({
Key? key,
required this.passwordUserText,
}) : super(key: key);
final TextEditingController passwordUserText;
@override
Widget build(BuildContext context) {
return TextField(
controller: passwordUserText,
cursorColor: Colors.red,
cursorHeight: 25,
style: TextStyle(fontSize: 20),
obscureText: true,
decoration: InputDecoration(
contentPadding: EdgeInsets.all(20),
hintText: 'Пароль',
hintStyle: TextStyle(fontSize: 20),
prefixIcon: Icon(
Icons.security,
color: Colors.red,
),
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: const BorderRadius.all(
Radius.circular(15),
),
),
filled: true,
fillColor: Colors.white),
);
}
}
/////////////////////////// LOGIN FIELD /////////////////////////////////////
class LoginFieldWidget extends StatelessWidget {
它似乎工作正常,但我不知道如何从 json 请求中获取 UserId 变量,以便我可以在其他屏幕或小部件中使用它来处理其他 json 请求,其中已经需要用户的 UserId .
最佳答案
final user = User.fromJson(parsed);
您可以使用下面的代码获取 UserId
final userId = user.result!.UserId;
关于json - Flutter获取Json并提取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68698273/