Flutter-Http请求被执行了几次,我不知道为什么吗?

时间:2020-03-09 14:27:51

标签: android http flutter dart mobile

我正在使用flutter,目前正在使用PHP获取数据库中的数据。我在PHP中使用选择查询,使用从SharedPreference变量中保存的ID来检索特定表中的所有数据,这部分工作正常。

我现在面临的问题是,当我加载页面以便它可以在应用程序加载时立即检索数据时,我想将要从数据库中检索的特定列的内容插入Card中它位于ListView内,使其成为Card Widget的列表,在获取其请求的数据时,它会返回一个列表,但会在Card Widget内创建一定数量的Card,以重复每张卡的列表内容,但我不明白为什么会这样。我想知道是否有什么可以解决我遇到的这个错误。我想要的输出是每张卡都包含我在Pref()类中声明的List的内容。在第106行的上方,当它表明来自数据库的数据正在传递并正确插入到列表中时,我放置了一条打印语句。

下面,我附了我的代码以及该数据被抓取了多少次的数据的屏幕截图以及该数据在我的设备上的外观的屏幕截图。

[我的设备的屏幕截图。] [1]

import 'package:flutter/material.dart';
import 'package:huna/bookings.dart';
import 'package:huna/dashboard.dart';
import 'package:huna/login.dart';
import 'package:huna/payment.dart';
import 'package:huna/feedback.dart';
import 'package:huna/favorites.dart';
import 'package:huna/messages.dart';
import 'package:huna/secondaryPages/myProfileSettings.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(MyProfile());

class MyProfile extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'HUNA',
      theme: ThemeData(
        primaryColor: Colors.grey.shade900,
        primarySwatch: Colors.blueGrey,
      ),
      home: MyProfilePage(),
    );
  }
}

class MyProfilePage extends StatefulWidget {
  @override
  _MyProfileState createState() => _MyProfileState();
}


class Pref {
  String username;
  String fName;
  String lName;
  String id;
  List <String> feedBackMap;
  int count;

  Pref({this.username, this.id, this.count, this.fName, this.lName, this.feedBackMap});
}
Pref p = new Pref();
final children = <Widget>[];



class _MyProfileState extends State<MyProfilePage> {
  @override

  void initState()  {
    getData();
    super.initState();

  }



  SharedPreferences _pref;

  void updatedPreferences(SharedPreferences preference){

    setState(() {
      return this._pref = preference;
    });

  }


  Future<Pref> getPref(Pref p) async{

    SharedPreferences preferences = await SharedPreferences.getInstance();
    setState(() {
      p.id = preferences.getString('id');
      p.username = preferences.getString("username");
    });

    return p;
  }




  Future getData() async{
    getPref(p);


    final response = await http.post("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", body: {

      "id": p.id
    });

    if(response.statusCode == 200){
      final data = jsonDecode(response.body);
      p.count = data.length;
      print(p.count.toString());
      print(data.length.toString());
      p.feedBackMap = new List <String>();
      for(int i = 0; i < data.length; i++){
        p.feedBackMap.add(data[i]['content']);
      }
      print(p.feedBackMap);




    }

  }


  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey.shade900,
      appBar: AppBar(
        title: Text('Profile'),
        elevation: 0,
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.settings),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => MyProfileSettings()),
              );
            },
          ),
        ],
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            UserAccountsDrawerHeader(
              accountName: Text('John Smith'),
              accountEmail: Text(p.username), //Use Username Instead
              currentAccountPicture: CircleAvatar(
                backgroundImage: AssetImage('assets/images/profile.jpg'),
              ),
              onDetailsPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => MyProfile()),
                );
              },
            ),
            ListTile(
                leading: Icon(Icons.home),
                title: Text('Dashboard'),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => Dashboard()),
                  );
                }),
            ListTile(
                leading: Icon(Icons.date_range),
                title: Text('Bookings'),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => Bookings()),
                  );
                }),
            ListTile(
                leading: Icon(Icons.question_answer),
                title: Text('Messages'),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => Messages()),
                  );
                }),
            ListTile(
                leading: Icon(Icons.favorite),
                title: Text('Favorites'),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => Favorites()),
                  );
                }),
            ListTile(
                leading: Icon(Icons.credit_card),
                title: Text('Payment'),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => Payment()),
                  );
                }),
            Divider(),
            ListTile(
                leading: Icon(Icons.info),
                title: Text('About Us'),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => FeedbackPage()),
                  );
                }),
            ListTile(
                leading: Icon(Icons.exit_to_app),
                title: Text('Logout'),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => LoginPage()),
                  );
                }),
          ],
        ),
      ),
      body: StudentProfileWidget(),
    );
  }
}

class StudentProfileWidget extends StatelessWidget {


  @override
  Widget build(BuildContext context) {

    for(int i = 0; i < p.count; i++){
      children.add(
        Card( 
        child: ListTile(
        contentPadding: EdgeInsets.all(20),
        subtitle: Text(
          p.feedBackMap[i],
          ),
          isThreeLine: true,
        ),
     ),);
    }

    return Stack(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 180),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(35),
              topRight: Radius.circular(35),
            ),
          ),
        ),
        Container(
          padding: EdgeInsets.only(),
          child: Align(
            alignment: Alignment.topCenter,
            child: Column(
              children: <Widget>[
                CircleAvatar(
                  radius: 40,
                  backgroundImage: AssetImage('assets/images/profile.jpg'),
                ),
                SizedBox(height: 20),
                // Profile Text
                Center(
                  child: Text(
                    ' ',
                    style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.white),
                  ),
                ),
                Center(
                  child: Text(
                    p.username,
                    style: TextStyle(color: Colors.white70),
                  ),
                ),
                SizedBox(height: 20),
                // Location
                Padding(
                  padding: const EdgeInsets.only(left: 25.0, right: 25.0),
                  child: Row(
                    children: <Widget>[
                      Icon(
                        Icons.location_on,
                        color: Colors.white,
                        size: 15,
                      ),
                      Text(
                        ' Cebu City, Philippines',
                        style: TextStyle(color: Colors.white, fontSize: 12),
                      ),
                    ],
                  ),
                ),
                // Reviews and Average Star Ratings
                Padding(
                  padding: const EdgeInsets.only(
                      left: 25.0, top: 30.0, right: 25.0, bottom: 10.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      // Reviews Label
                      Text(
                        'Reviews',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      // Average Star Ratings
                      Container(
                        child: Row(
                          children: <Widget>[
                            Icon(Icons.star, size: 20),
                            Icon(Icons.star, size: 20),
                            Icon(Icons.star, size: 20),
                            Icon(Icons.star, size: 20),
                            Icon(Icons.star, size: 20),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: ListView(
                    shrinkWrap: true,
                    padding: EdgeInsets.all(15),
                    children: children,
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}


  [1]: https://i.stack.imgur.com/oj4Wp.jpg

0 个答案:

没有答案