简体   繁体   中英

Flutter returning null while trying to acquire data from php backend

Here is my frontend code. I's sincerely frustrated about what could be going on here.

I want to collect data to a flutter app from a serverside php code..

The function responsible for this connection is in the Future _getPosts() function in the MyScaffold class.

class MyScaffold extends StatelessWidget{
  @override
  Widget build(BuildContext context){
  return Scaffold(
        appBar: AppBar(
          title: Text("ENPOWER DISCUSSION"),
          backgroundColor: Colors.green,
        ),
        drawer: Drawer(
        child: ListView(
          children: <Widget>[
            ListTile(
              title: Text("GENERAL FEEDS"),
              onTap:(){
                Navigator.of(context).pop(); //
              }
            ),
            ListTile(
              title: Text("ENROLLMENT"),
              onTap:(){
                Navigator.of(context).pop(); // Close Navigator
                //Call a new function here

                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => EnrollmentPage()),
                );                
              }              

            ),
            ListTile(
              title: Text("PAYMENT"),
              onTap:(){
                Navigator.of(context).pop(); // Close Navigator
                //Call a new function here

                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => PaymentPage()),
                );                
              }
            ),
            ListTile(
              title: Text("FAQ"),
              onTap:(){
                Navigator.of(context).pop(); // Close Navigator
                //Call a new function here
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => FaqPage()),
                );
              }
            ),                                    
          ],
        ),
      ), 
      body: Container(
        child: FutureBuilder(
          future: _getPosts(),
          builder: (BuildContext context, AsyncSnapshot snapshot){
            print(snapshot.data);
            if(snapshot.data == null){
              return Container(
                child: Center(child: Text("Processing..."),),
              );
            }else{
              return ListView.builder(itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index){
                  return ListTile(
                    title: Text(snapshot.data[index].postTitle),
                  );
                },
              );
            }
          },
        ),
      ),       
      );

  }

  Future<List<Post>> _getPosts() async{
    var data = await http.get("www.empowermentopportunities.com/xxyyzz/admin_panel/backend/api_connector.php");
    var jsonData = json.decode(data.body);

    List<Post> posts = [];

    for(var p in jsonData){
      Post post = Post(p["post_id"], p["post_title"], p["post_content"], p["post_image_url"], p["post_date"]);
      posts.add(post);
    }

    print(posts.length);
    return posts;
  }

}


class Post{
  final int postId;
  final String postTitle;
  final String postContent;
  final String postImageurl;
  final String postDate;

  Post(this.postId, this.postTitle, this.postContent, this.postImageurl, this.postDate);
}
void main(){
  runApp(MaterialApp(
    title: 'My app',
    home: MyScaffold(),
  ));
}

This is the server side php code whose role is to collect the data from the database and then compress it to JSON before sending it to the front end caller.

function fetch_gen_data($offset, $total){
    include "../db/connection.php";
    $data = array();

    $query = mysqli_query($con, "SELECT * FROM posts ORDER BY post_id DESC LIMIT $total OFFSET $offset")or die(mysqli_error($con));

    if(mysqli_num_rows($query)>0){

            while($row = mysqli_fetch_assoc($query)){
                $data[] = $row;



            }


    }
    return json_encode(json_encode($data));
}

I then invoke that function from another one

echo fetch_gen_data(0, 10);

I think the problem is the double json encoding in the backend. If you see the response is a string and not a json.

Just go to http://www.empowermentopportunities.com/xxyyzz/admin_panel/backend/api_connector.php via browser and you'll see.

The return should be return json_encode($data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM