Home > Blockchain >  API give data NULL in first Load
API give data NULL in first Load

Time:06-30

I get the data from API and when API calls on the first load of the screen so API gets the data but in response, the data shows the null value, and when I click on hot reload it response shows data from API. I don't know what happens with API or response. Please someone help me to understand what happened with the response I also used await but nothing happens.

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';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:mindmatch/utils/Auth.dart';


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;
final body = null;
@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.******.net', '/mm_api/index.php',{'act':'profile','UsrID': UsrID});
print(url);



// print(getData());

Future getData() async{
  final  res = await http.get(
      url,
    headers: {'Content-Type': 'application/json'},
  );
  //var res = await http.get(Uri.parse('www.*******.net/mm_api/index.php?act=profile&UsrID=${UsrID}'));
  print(res);
  //data = json.decode(res.body);
  data = jsonDecode(res.body);
  print(data);
  //setState(() {});
  //print(res.body);
}

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

print(data);
//print(getData());


//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(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
            begin: Alignment.topRight,
            end: Alignment.bottomLeft,
            //colors: const [Color.fromRGBO(132,105,211,1), Color.fromRGBO(93,181,233,1), Color.fromRGBO(86,129,233,1)],
            colors: [Colors.white, Colors.white]
        ),
      ),
      width: size.width,
      height: size.height,
      child: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              //addVerticalSpace(30),

              data != null?Expanded(
                  child: Padding(
                    padding: sidePadding,
                    child: ListView(
                      physics: BouncingScrollPhysics(),
                      children: [
                        Text('${data[0]['name']}')
                      ],
                    ),
                  )
              ): const Center(
                child: CircularProgressIndicator(),
              )
            ],
          ),
        ],
      )
  ),

  drawer: Sidebar(),

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

);
//);
}
}

When first load screen it shows me a null value:- Here I Print data form response but it shows me a null value

And when I hot reload the screen it shows me the response value:- It shows the value and I comment any print value or hot reload the screen

Data from API:-

[{"id":"1","name":"anni","fulname":"anni ann","mobile":" 15214639870","email":"[email protected]","about":"sdhbsdbcshcbsdhcbsbchsdb\ncbhbchsc","lookfor":"Relationship, Networking","education":"gcnd,2018","work":"dhfjsk,fjskk","politics":"Liberal, Apolitical","religion":"Protestant, Anglican, Hindu","children":"Have   don&#39;t want more, Have and want more","interests":"Treking, Sports, Cooking","distance":" 17 ","age":" 20, 60 "}]

when I test API on the browser it shows correct data but does not show in response WHY?

Please help me to understand this. I don't know whats going on with the response

CodePudding user response:

It also looks like you are calling initState in your build method. You have to move it out of build method as it is a separate override method.

CodePudding user response:

You have to call setstate after catching data from api

add this line in your getdata() at the end setstate()

setstate() is used to hot reload programatically so in other words when your app update it's state or any information which is used by your app you have to call setstate() function for reflate on your app's ui.

setstate() function call build method one time again and draw whole tree again.

if you have not use setstate then i suggest some code below do this.

  final  res = await http.get(
      url,
    headers: {'Content-Type': 'application/json'},
  );
  //var res = await http.get(Uri.parse('www.*******.net/mm_api/index.php?act=profile&UsrID=${UsrID}'));
  print(res);
  //data = json.decode(res.body);
  dynamic data = jsonDecode(res.body);
  print(data);
  return data;
  //setState(() {});
  //print(res.body);
}

//then edit your future builder

FutureBuilder(builder: (context, snapshot) {
  if(snapshot.connectionState==ConnectionState.waiting){
    //return loader
  }else {
    if(snapshot.hasData==true){
      //update your ui
    }else{
      //data is null
    }
  }
}```
  • Related