Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter get Json and extract variable

Tags:

json

flutter

dart

Im newbie to dart/flutter.

I wrote a code that takes values ​​from input fields and substitutes a link in url to check authorization and returns the following response:

  "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
}

I wrote the code in button method,

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 {

It seems to work fine, but I cannot figure out how I can get the UserId variable from the json request so that I can use it in other screen or widgets for other json requests, where the UserId of the user is already required.

like image 363
Чак Джонс Avatar asked Nov 23 '25 20:11

Чак Джонс


1 Answers

final user = User.fromJson(parsed);

You can get UserId by using this code below

final userId = user.result!.UserId;
like image 125
Faizan Darwesh Avatar answered Nov 25 '25 09:11

Faizan Darwesh