У меня есть ответ тела json из API входа в систему. Я создал класс модели для этого json. Теперь как использовать его на моих страницах для извлечения данных?

#json #flutter #api #model

#json #flutter #API #Модель

Вопрос:

Я вошел в систему из api. Затем я получил ответ json. Я могу извлекать данные из входа на домашнюю страницу. Для этого я создал конструктор на домашней странице и передал его на странице входа в систему, где я создал навигатор для домашней страницы. Но я знаю, что не рекомендуется извлекать подобные данные. использование класса модели — более разумный способ. Я добавил сюда свой код входа, домашней страницы и модели. Теперь мои данные могут обмениваться данными только между этими двумя страницами. Но мне нужно также извлекать данные на другие страницы.

login.dart

     import 'package:api_login/model/response_model.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

import '../sharePreference.dart';
import 'homepage.dart';


class Login extends StatefulWidget {
  UserDetails userDetails = new UserDetails();
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {

var notification ;
  bool isprocesscomplete = false;
  TextEditingController _userController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  String BaseUrl = "my url";


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      body: SingleChildScrollView(
        child: Center(
          child: Container(
            height: 770,
             color:  Colors. lightBlue,
            padding: EdgeInsets.fromLTRB(20, 100, 20, 20),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [

                Text(
                  "Login",
                  style: TextStyle(fontSize: 32),
                ),
                SizedBox(
                  height: 30,
                ),
                Card(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Container(
                    height: 220,
                    width: MediaQuery.of(context).size.width,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Column(
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(30),
                          child: TextField(
                            controller: _userController,
                            decoration: InputDecoration(hintText: "Username"),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(30),
                          child: TextField(
                            controller: _passwordController,
                            obscureText: true,
                            decoration: InputDecoration(hintText: "Password"),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  height: 60,
                  width: MediaQuery.of(context).size.width,
                  child: RaisedButton(
                    color: Colors.blue,
                    onPressed: () {
                      if (_userController.text == "" ||
                          _passwordController.text == "") {
                        final snackBar = SnackBar(
                            content: Text("Enter Username and Password"));
                        _scaffoldKey.currentState.showSnackBar(snackBar);
                      } else {
                        signIn(_userController.text, _passwordController.text);
                      }
                    },
                    child: ProgressButton(),
                    shape: RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(16),
                    ),
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                FlatButton(
                  child: Text("Forgot password"),
                  onPressed: () {},
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget ProgressButton() {
    if (isprocesscomplete != false) {
      return CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Colors.white));
    } else {
      return new Text(
        "Sign In",
        style: const TextStyle(
          color: Colors.white,
          fontSize: 15.0,
        ),
      );
    }
  }

  void signIn(String username, String password) async {
    setState(() {
      isprocesscomplete = true;
    });
    var response = await http.post(BaseUrl,
        headers: {"Content-Type": "application/json"},
        body: json.encode({
          "username": username,
          "password": password,
        }));

    Map<String, dynamic> value = json.decode(response.body);
    notification = value["notifications"];
    // print('Response ${response.body}');
    if (response.statusCode == 200) {
      try {
        ///You don't need it but it will be cool for show progress dialgo for 4 second then redirect even if we get reslut
        Future.delayed(Duration(seconds: 4), () {
          // 5s over make it false
          setState(() {
            isprocesscomplete = true;
          });
        });
        Map<String, dynamic> value = json.decode(response.body);
        print('Response ${response.body}');
        SharedPrefrence().setToken(value['api_token'].toString());
        SharedPrefrence().setName(value['user_name']);
        SharedPrefrence().setUserId(value['user_id'].toString());

        ///This is used when user loged in you can set this true,
        ///next time you open you need to check loginc in main.dart or splashscreen if this is true if it is true then
        ///redirect to home page it is false then redirect to Login page
        ///When you logout the app make sure you set this as false like "SharedPrefrence().setLoggedIn(false);"
        SharedPrefrence().setLoggedIn(true);

        ///Redirect to Home page
        Navigator.pushAndRemoveUntil(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => HomePage(
                                      user_name: value['user_name'],
                                      api_token: value['api_token'],
                                      notification: notification,
                                     // payment: payment ,
                                    )),
                                ModalRoute.withName("/login"));

      } catch (e) {
        e.toString();
        final snackBar =
        SnackBar(
            content: Text("something wrong,Try again 😑"),
          behavior: SnackBarBehavior.floating,
        );
        _scaffoldKey.currentState.showSnackBar(snackBar);
      }
    } else {
      var message = value['error'];
      final snackBar = SnackBar( backgroundColor: Colors.redAccent[700],
          content: Text(message.toString()),
        behavior: SnackBarBehavior.floating, );
      _scaffoldKey.currentState.showSnackBar(snackBar);
    }
  }
}
  

homepage.dart

     import 'package:api_login/model/response_model.dart';
import 'package:api_login/pages/details.dart';
import 'package:api_login/pages/settingPage.dart';
import 'package:api_login/widget/neumorphsm.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../sharePreference.dart';
import 'login.dart';
import 'login.dart';

class HomePage extends StatefulWidget {
 final payment;
  final count ;
  String user_name;
  final api_token;
  final user_id ;
  final payment_id;
  final  List<dynamic> notification ;
  // List data ;
  HomePage({ this.user_name, this.api_token , this.user_id, @required this.notification ,
             this.count, this.payment, this.payment_id});


  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  String arrayLength ;
  String nametoprint;
  String tokentoprint;

  @override
  void initState() {
    super.initState();
    Future name = SharedPrefrence().getName();
    name.then((data) async {
      nametoprint = data;
      print(nametoprint);
    });
    Future token= SharedPrefrence().getToken();
    token.then((data) async {
      tokentoprint= data;
      print(tokentoprint);
    });
  }
  int counter ;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(

          title: Text("Cash-Management"),
          backgroundColor: Colors.blue,
          actions: [
            new Stack(
              children: <Widget>[
                new IconButton(icon: Icon(Icons.notifications), onPressed: () {
                  setState(() {
                    counter = 0;
                  });
                }),
                counter != 0 ? new Positioned(
                  right: 11,
                  top: 11,
                  child: new Container(
                    padding: EdgeInsets.all(2),
                    decoration: new BoxDecoration(
                      color: Colors.red,
                      borderRadius: BorderRadius.circular(6),
                    ),
                    constraints: BoxConstraints(
                      minWidth: 14,
                      minHeight: 14,
                    ),
                    child: Text(
                      "  ${widget.notification.length} ",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 8,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ) : new Container()
              ],
            ),
            IconButton(
                icon: Icon(Icons.exit_to_app),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => Login()),
                  );
                }),
          ],
        ),
        body: ListView(
          children: <Widget>[
            Card(
              color: Colors.lightBlue,
              child: InkWell(
                onTap: () {
                  Navigator.push(
                      context,
                      new MaterialPageRoute(
                          builder: (BuildContext context) =>
                          new SettingPage()));
                },
                child: Container(
                  height: 120,
                  child: Column(

                   mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        "Profile",
                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                      Text(
                        "Name:${widget.user_name}",
                        // "  ${widget.username} ",
                        style: TextStyle(fontSize: 16),
                      ),
                      // Text(
                      //   "  ${widget.notification.length} ",),
                      // Text(" ${nametoprint} "),
                    ],
                  ),
                ),
              ),
            ),

Container(
  color: Colors.lightBlue,
  height: 400,
  child:   ListView.builder(
      itemCount: widget.notification == null ?  0 : widget.notification.length,
      itemBuilder: (context, index){
        final count = widget.notification ;
                   print(count.length);
        return Card(

            color: Colors.blue,
            child: InkWell(
              onTap: () {
                Navigator.push(
                    context,
                    new MaterialPageRoute(
                        builder: (BuildContext context) =>
                        new DetailPage()));
              },
              child: Column(
                children:<Widget>[
Text('Amount'),
               ListTile(
                 title: Text(widget.notification[index] ["data"]["amount"].toString()),
                 subtitle: Text(widget.notification[index]["data"]["message"].toString()),
                  )  ,
                 Text('Created at '),

                  ListTile(
                    title: Text(widget.notification[index] ["created_at"].toString()),
                  ),
Text('updated at'),
                  ListTile(
                    title: Text(widget.notification[index] ["updated_at"].toString()),
                  ),
          ],
              ),
            ),
        );
      }),
),

            Container(
              color: Colors.blue,
              height: 130,
              child: Button()
            ),
          ],
        ),

        // floatingActionButton: FloatingActionButton(onPressed: () {
        //   print("Increment Counter");
        //   setState(() {
        //     counter  ;
        //   });
        // }, child: Icon(Icons.add),),
      ),
    );


  }

}
  

response_model.dart

 class UserDetails {
  int userId;
  String userName;
  String apiToken;
  List<Notifications> notifications;

  UserDetails({this.userId, this.userName, this.apiToken, this.notifications});

  UserDetails.fromJson(Map<String, dynamic> json) {
    userId = json['user_id'];
    userName = json['user_name'];
    apiToken = json['api_token'];
    if (json['notifications'] != null) {
      notifications = new List<Notifications>();
      json['notifications'].forEach((v) {
        notifications.add(new Notifications.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['user_id'] = this.userId;
    data['user_name'] = this.userName;
    data['api_token'] = this.apiToken;
    if (this.notifications != null) {
      data['notifications'] =
          this.notifications.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Notifications {
  String id;
  String type;
  int notifiableId;
  String notifiableType;
  Data data;
  Null readAt;
  String createdAt;
  String updatedAt;

  Notifications(
      {this.id,
        this.type,
        this.notifiableId,
        this.notifiableType,
        this.data,
        this.readAt,
        this.createdAt,
        this.updatedAt});

  Notifications.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    type = json['type'];
    notifiableId = json['notifiable_id'];
    notifiableType = json['notifiable_type'];
    data = json['data'] != null ? new Data.fromJson(json['data']) : null;
    readAt = json['read_at'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['type'] = this.type;
    data['notifiable_id'] = this.notifiableId;
    data['notifiable_type'] = this.notifiableType;
    if (this.data != null) {
      data['data'] = this.data.toJson();
    }
    data['read_at'] = this.readAt;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    return data;
  }
}

class Data {
  int paymentId;
  String generatePaymentId;
  String message;
  int amount;

  Data({this.paymentId, this.generatePaymentId, this.message, this.amount});

  Data.fromJson(Map<String, dynamic> json) {
    paymentId = json['payment_id'];
    generatePaymentId = json['generate_payment_id'];
    message = json['message'];
    amount = json['amount'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['payment_id'] = this.paymentId;
    data['generate_payment_id'] = this.generatePaymentId;
    data['message'] = this.message;
    data['amount'] = this.amount;
    return data;
  }
}
  

Будет полезно, если кто-нибудь сообщит мне, как показать страницу с подробностями из этого раздела.

 ListView.builder(
      itemCount: widget.notification == null ?  0 : widget.notification.length,
      itemBuilder: (context, index){
        final count = widget.notification ;
                   print(count.length);
        return Card(

            color: Colors.blue,
            child: InkWell(
              onTap: () {
                Navigator.push(
                    context,
                    new MaterialPageRoute(
                        builder: (BuildContext context) =>
                        new DetailPage()));
              },
  

Ответ №1:

Вы можете использовать widget.user_name widget.api_token на домашней странице и передать его на страницу сведений.

Домашняя страница

 Navigator.push(
      context,
      new MaterialPageRoute(
       builder: (BuildContext context) =>
         new DetailPage(userName :widget.user_name, apiToken: widget.api_token)));
  

Комментарии:

1. Это не работает, брат. Я также попытался установить конструктор на странице сведений с именем пользователя, apiToken. У вас есть решение. Будет полезно, если вы отредактируете некоторый код на моей странице. Заранее спасибо.

Ответ №2:

Если вы хотите, чтобы данные использовались в вашем приложении глобально, возможно, вы можете извлечь свои данные из API перед MaterialApp(), чтобы ваши данные можно было использовать глобально.

Другой способ — вы можете передать свои данные UserDetails() на следующую страницу, вызвав их внутри вашего Navigator.push() . Вы можете прочитать более подробный пример здесь