Search code examples
phpflutterapiflutter-dependenciesflutter-http

Get data from API With Dynamic userid in API


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


Solution

  • 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