简体   繁体   English

Flutter 在尝试从 php 后端获取数据时返回 null

[英]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..我想从服务器端 php 代码收集数据到 flutter 应用程序。

The function responsible for this connection is in the Future _getPosts() function in the MyScaffold class.负责此连接的函数位于 MyScaffold 类中的 Future _getPosts() 函数中。

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.这是服务器端php代码,其作用是从数据库中收集数据,然后将其压缩为JSON,然后再发送给前端调用者。

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.我认为问题在于后端的双 json 编码。 If you see the response is a string and not a json.如果您看到响应是字符串而不是 json。

Just go to http://www.empowermentopportunities.com/xxyyzz/admin_panel/backend/api_connector.php via browser and you'll see.只需通过浏览器访问 http://www.empowermentopportunities.com/xxyyzz/admin_panel/backend/api_connector.php ,您就会看到。

The return should be return json_encode($data);返回应该是return json_encode($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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