我有一个来自登录API的json body响应。我为这个json创建了一个模型类。现在如何在我的页面中使用它来获取数据?

我有一个来自登录API的json body响应。我为这个json创建了一个模型类。现在如何在我的页面中使用它来获取数据?,json,api,flutter,model,details,Json,Api,Flutter,Model,Details,我已从api登录。然后我得到了json的响应。我可以从登录到主页获取数据。为此,我在主页中创建了一个构造器,并将其传递到登录页面,在该页面中我为主页创建了导航器。但我知道这样获取数据不是一个好的做法。使用模型类是更聪明的方法。我在这里添加了登录、主页和模型的代码。现在我的数据只能在这两个页面之间进行通信。但我也需要把数据拿到另一个页面 login.dart import 'package:api_login/model/response_model.dart'; import 'pack

我已从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 You can use 
widget.user_name
,
widget.api_token
in HomePage, and pass it to Details Page.

Home Page

Navigator.push(
      context,
      new MaterialPageRoute(
       builder: (BuildContext context) =>
         new DetailPage(userName :widget.user_name, apiToken: widget.api_token)));
import'包:api_login/model/response_model.dart';
进口“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
导入“dart:convert”;
导入“../sharePreference.dart”;
导入“homepage.dart”;
类登录扩展StatefulWidget{
UserDetails UserDetails=新的UserDetails();
@凌驾
_LoginState createState()=>\u LoginState();
}
类_LoginState扩展了状态{
风险值通知;
bool isprocesscomplete=false;
TextEditingController _userController=TextEditingController();
TextEditingController_passwordController=TextEditingController();
最终_scaffoldKey=GlobalKey();
String BaseUrl=“我的url”;
@凌驾
小部件构建(构建上下文){
返回脚手架(
钥匙:_scaffoldKey,
正文:SingleChildScrollView(
儿童:中心(
子:容器(
身高:770,
颜色:颜色。浅蓝色,
填充:来自LTRB(20,100,20,20)的边缘设置,
子:列(
mainAxisAlignment:mainAxisAlignment.center,
crossAxisAlignment:crossAxisAlignment.center,
儿童:[
正文(
“登录”,
样式:TextStyle(字体大小:32),
),
大小盒子(
身高:30,
),
卡片(
形状:圆形矩形边框(
边界半径:边界半径。圆形(20),
),
子:容器(
身高:220,
宽度:MediaQuery.of(context).size.width,
装饰:盒子装饰(
边界半径:边界半径。圆形(20),
),
子:列(
儿童:[
填充物(
填充:常量边集。全部(30),
孩子:TextField(
控制器:_userController,
装饰:输入装饰(hintText:“用户名”),
),
),
填充物(
填充:常量边集。全部(30),
孩子:TextField(
控制器:_passwordController,
蒙昧文字:对,
装饰:输入装饰(hintText:“密码”),
),
),
],
),
),
),
大小盒子(
身高:60,
宽度:MediaQuery.of(context).size.width,
孩子:升起按钮(
颜色:颜色,蓝色,
已按下:(){
如果(_userController.text==“”||
_passwordController.text==“”){
最终蛇杆=蛇杆(
内容:文本(“输入用户名和密码”);
_scaffoldKey.currentState.showSnackBar(snackBar);
}否则{
登录(_userController.text,_passwordController.text);
}
},
子项:ProgressButton(),
形状:圆形矩形边框(
边界半径:新边界半径。圆形(16),
),
),
),
大小盒子(
身高:20,
),
扁平按钮(
子项:文本(“忘记密码”),
按下:(){},
),
],
),
),
),
),
);
}
窗口小部件ProgressButton(){
if(isprocesscomplete!=false){
返回循环预测器(
valueColor:AlwaysStoppedAnimation(Colors.white));
}否则{
返回新文本(
“登录”,
样式:consttextstyle(
颜色:颜色,白色,
字体大小:15.0,
),
);
}
}
无效登录(字符串用户名、字符串密码)异步{
设置状态(){
isprocesscomplete=true;
});
var response=wait http.post(BaseUrl,
标题:{“内容类型”:“应用程序/json”},
正文:json.encode({
“用户名”:用户名,
“密码”:密码,
}));
Map value=json.decode(response.body);
通知=值[“通知”];
//打印('Response${Response.body}');
如果(response.statusCode==200){
试一试{
///你不需要它,但它会很酷的显示进度拨号4秒,然后重定向,即使我们得到重新lut
未来。延迟(持续时间(秒:4),(){
//让它成为假的
设置状态(){
isprocesscomplete=true;
});
});
Map value=json.decode(response.body);
打印('Response${Response.body}');
SharedPreference().setToken(值['api_token'].toString());
SharedPreference().setName(值['user_name']);
SharedPreference().setUserId(值['user_id'].toString());
///当用户登录时使用,您可以将其设置为true,
///下次打开时,您需要在main中检查loginc