通过API中的Dynamic UserID从API获取数据

发布于 2025-02-11 08:23:45 字数 5072 浏览 3 评论 0原文

我想从API中获取配置文件数据,但每个尝试击中API的人都会向我显示“未来”实例的错误。

错误: - 在屏幕加载期间或重新加载期间在控制台中显示错误

,以及如果我打印了URL分别自动击中API两次,我只击中一次。

如果我尝试打印一些数据,它将向我显示错误在打印任何数据期间的错误显示

是我的代码: -

import 'package:flutter/material.dart';
import 'package:mindmatch/utils/widget_functions.dart';
import 'package:mindmatch/screens/Favorites.dart';
import 'package:mindmatch/screens/Editprofile.dart';
import 'package:getwidget/getwidget.dart';
import 'package:mindmatch/screens/Sidebar.dart';
import 'package:mindmatch/screens/Footer.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';


class Profile extends StatefulWidget {
 var usrid;

 Profile({Key? key, @required this.usrid}) : super(key: key);

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



class _Profile extends State<Profile>{

//SingingCharacter? _character = SingingCharacter.male;
var url;
var data;

@override
Widget build(BuildContext context){
 var UsrID = widget.usrid;
 final Size size = MediaQuery.of(context).size;
 final ThemeData themeData = Theme.of(context);
 final double padding = 25;
 final sidePadding = EdgeInsets.symmetric(horizontal: padding);

     var url = Uri.https('www.algowid.net', '/mm_api/index.php',{'act':'profile','UsrID': UsrID});
print(url);



// print(getData());

Future getData(Usr) async{
  var res = await http.get(url);
  print(res);
  data = json.decode(res.body);
  print(data);
  setState(() {});
  print(res.body);
}

@override
void initState() async{
  super.initState();
  getData(UsrID);
  //print (getData(UsrID));
}

// print(data['fname']);
print(getData(UsrID));

//return SafeArea(
return Scaffold(
  appBar: AppBar(
    titleSpacing: 3,
    backgroundColor: Colors.white,
    elevation: 0,
    title: Text('My Profile', style: TextStyle(color: Colors.black, fontSize: 15,),),
    leading: Builder(
      builder: (BuildContext context) {
        return Padding(padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
          child: IconButton(
            icon: SvgPicture.asset(
              width: 30,
              'assets/images/Menu.svg',
              height: 30,
            ),
            onPressed: () { Scaffold.of(context).openDrawer(); },
            tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
          ),
        );
      },
    ),
    actions: <Widget>[
      Padding(
          padding: sidePadding,
          child: Row(
            children: [
              //Icon(Icons.search, color: Colors.black,),
              SvgPicture.asset(
                width: 30,
                'assets/images/search.svg',
                height: 30,
              ),
            ],
          )

      )

    ],

  ),
  backgroundColor: Color(0xff8f9df2),
  body: Container(
     child: Text("data['fname']"),
   ),
  ),

  drawer: Sidebar(),

  persistentFooterButtons: [
    Footer(usrid:UsrID),
  ],

);
//);
}
}


final List<String> imgs = [
 "assets/images/people.png",
 "assets/images/people.png",
 "assets/images/people.png",
 "assets/images/people.png",
 "assets/images/people.png",
];



class PersonImages extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
  return GFItemsCarousel(
   rowCount: 3,
  //itemHeight: MediaQuery.of(context).size.height / 1.5,
   children: imgs.map(
        (url) {
      return Container(
        margin: EdgeInsets.all(5.0),
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(8.0)),
          child:
          Image.asset(url, fit: BoxFit.cover,),
        ),
      );
    },
  ).toList(),
);
}
}

这是我的API代码: -

case"profile":
    $json = [];
    //if(isset($_REQUEST)){
    $user = filter_input(INPUT_GET, 'UsrID', FILTER_SANITIZE_STRING);
    
$profile = $db->query("SELECT * FROM users WHERE id ='$user' ");
  $profileAry = $profile->fetch_assoc();

    $json[] = [
    'id'=>$profileAry['id'], 
    'fname'=> $profileAry['fname']." ".$profileAry['lname'], 
    'mobile'=> $profileAry['ccode'].$profileAry['phone'], 
    'email'=> $profileAry['email'], 
    'about'=> $profileAry['about'], 
    'lookfor'=> $profileAry['lookfor'], 
    'education'=> $profileAry['edu_institute'].','.$profileAry['edu_year'], 
    'work'=> $profileAry['work_job'].','.$profileAry['work_company'], 
    'politics'=> $profileAry['politics'], 
    'religion'=> $profileAry['religion'],
    'children'=> $profileAry['children'], 
    'interests'=> $profileAry['intersets']
    ];

    //}
echo json_encode($json);

break;

请帮助我如何从API中显示这些数据。 当击中API时,它会自动添加循环。 请帮助我。

当我打印GetData(USRID)时,为什么会在循环中击中API,它一次又一次地打印数据。请参阅此图像: - 请参阅我的控制台,我在其中打印了detdata(usrid),并显示数据a < /a>

我只想一次打印一次数据。 请我出去

I want to get profile data from API with userid but every I try to hit the API it shows me the error of Instance of 'Future'.

Error:- Error shows in the console during screen load or reload

And also if I print the URL separately it automatically hits the API two times I just hit only one time.

And if I tried to print some data it show me an error Error show during print any data

Here is my code:-

import 'package:flutter/material.dart';
import 'package:mindmatch/utils/widget_functions.dart';
import 'package:mindmatch/screens/Favorites.dart';
import 'package:mindmatch/screens/Editprofile.dart';
import 'package:getwidget/getwidget.dart';
import 'package:mindmatch/screens/Sidebar.dart';
import 'package:mindmatch/screens/Footer.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';


class Profile extends StatefulWidget {
 var usrid;

 Profile({Key? key, @required this.usrid}) : super(key: key);

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



class _Profile extends State<Profile>{

//SingingCharacter? _character = SingingCharacter.male;
var url;
var data;

@override
Widget build(BuildContext context){
 var UsrID = widget.usrid;
 final Size size = MediaQuery.of(context).size;
 final ThemeData themeData = Theme.of(context);
 final double padding = 25;
 final sidePadding = EdgeInsets.symmetric(horizontal: padding);

     var url = Uri.https('www.algowid.net', '/mm_api/index.php',{'act':'profile','UsrID': UsrID});
print(url);



// print(getData());

Future getData(Usr) async{
  var res = await http.get(url);
  print(res);
  data = json.decode(res.body);
  print(data);
  setState(() {});
  print(res.body);
}

@override
void initState() async{
  super.initState();
  getData(UsrID);
  //print (getData(UsrID));
}

// print(data['fname']);
print(getData(UsrID));

//return SafeArea(
return Scaffold(
  appBar: AppBar(
    titleSpacing: 3,
    backgroundColor: Colors.white,
    elevation: 0,
    title: Text('My Profile', style: TextStyle(color: Colors.black, fontSize: 15,),),
    leading: Builder(
      builder: (BuildContext context) {
        return Padding(padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
          child: IconButton(
            icon: SvgPicture.asset(
              width: 30,
              'assets/images/Menu.svg',
              height: 30,
            ),
            onPressed: () { Scaffold.of(context).openDrawer(); },
            tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
          ),
        );
      },
    ),
    actions: <Widget>[
      Padding(
          padding: sidePadding,
          child: Row(
            children: [
              //Icon(Icons.search, color: Colors.black,),
              SvgPicture.asset(
                width: 30,
                'assets/images/search.svg',
                height: 30,
              ),
            ],
          )

      )

    ],

  ),
  backgroundColor: Color(0xff8f9df2),
  body: Container(
     child: Text("data['fname']"),
   ),
  ),

  drawer: Sidebar(),

  persistentFooterButtons: [
    Footer(usrid:UsrID),
  ],

);
//);
}
}


final List<String> imgs = [
 "assets/images/people.png",
 "assets/images/people.png",
 "assets/images/people.png",
 "assets/images/people.png",
 "assets/images/people.png",
];



class PersonImages extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
  return GFItemsCarousel(
   rowCount: 3,
  //itemHeight: MediaQuery.of(context).size.height / 1.5,
   children: imgs.map(
        (url) {
      return Container(
        margin: EdgeInsets.all(5.0),
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(8.0)),
          child:
          Image.asset(url, fit: BoxFit.cover,),
        ),
      );
    },
  ).toList(),
);
}
}

And here is my API code:-

case"profile":
    $json = [];
    //if(isset($_REQUEST)){
    $user = filter_input(INPUT_GET, 'UsrID', FILTER_SANITIZE_STRING);
    
$profile = $db->query("SELECT * FROM users WHERE id ='$user' ");
  $profileAry = $profile->fetch_assoc();

    $json[] = [
    'id'=>$profileAry['id'], 
    'fname'=> $profileAry['fname']." ".$profileAry['lname'], 
    'mobile'=> $profileAry['ccode'].$profileAry['phone'], 
    'email'=> $profileAry['email'], 
    'about'=> $profileAry['about'], 
    'lookfor'=> $profileAry['lookfor'], 
    'education'=> $profileAry['edu_institute'].','.$profileAry['edu_year'], 
    'work'=> $profileAry['work_job'].','.$profileAry['work_company'], 
    'politics'=> $profileAry['politics'], 
    'religion'=> $profileAry['religion'],
    'children'=> $profileAry['children'], 
    'interests'=> $profileAry['intersets']
    ];

    //}
echo json_encode($json);

break;

Please help me with how I Show this data from API.
It automatically adds the loop when API is hit.
Please help me out.

Why does it hit the API in the loop when I print getData(UsrID) it prints the data again and again. Please see this image:- see my console where i print the detData(UsrID) and it show the data a

I want to print this data only one time.
please me out

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

忆悲凉 2025-02-18 08:23:45

自然而然地,对API的调用是 asynchronous 。返回数据getData,然后使用FutureBuilder重建小部件。

请参阅逐步指令:从Internet获取数据

Naturally the call to API is asynchronous. Return data from getData and use FutureBuilder to rebuild widgets.

See step by step instructions: Fetch data from the internet

折戟 2025-02-18 08:23:45

直到我能够理解您试图调用“ getData()”功能的代码,请等待”,因此仅打印'Future'的实例

尝试使用打印(等待GetData());

till i am able to understand your code you trying to call "getData()" function with out "await" so its printing only Instance of 'Future'

try to use print(await getData());

秉烛思 2025-02-18 08:23:45

您要打印“ fname”的数据在JSON对象或数组中,您必须提供完整的路径。
例如:

{
    "body": [
       {
            "id": 1,
            "fname": "MyName",
       }
       {
            "id": 2,
            "fname": "MyName2",
       }
   ]
}

您必须像

print(data["body"][0]["fname"]);

输出一样打印它:

MyName

the data you are trying to print 'fname' is inside the JSON object or array, you have to provide the full path.
for eg:

{
    "body": [
       {
            "id": 1,
            "fname": "MyName",
       }
       {
            "id": 2,
            "fname": "MyName2",
       }
   ]
}

you have to print it like

print(data["body"][0]["fname"]);

Output:

MyName
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文