Flutter中的Future构建器获取数据两次。

huangapple go评论68阅读模式
英文:

The Future builder in Flutter is fetching data twice

问题

以下是代码部分的翻译:

class StudentListView extends StatefulWidget {
  @override
  State<StudentListView> createState() => _StudentListViewState();
}

class _StudentListViewState extends State<StudentListView> {

  List<StudentModel> students = [];

  late Future myFuture;

  Future<List<StudentModel>> getStudents() async {

    var response = await http.get(Uri.https(BASE_URL, APP_INTERSNSHIP_URL));

    var studentData = jsonDecode(response.body);

    for (var student in studentData) {

      final singlestudent = StudentModel(
          id: student["id"],
          name: student["name"]);
      students.add(singleStudent);
    }
    return students;
  }

  @override
  void initState() {
    myFuture = getStudents();
    super.initState();
  }

  Widget build(BuildContext context) {
    getStudents();
    return Scaffold(
      appBar: AppBar(
        title: Text(
          APP_TITLE,
        ),
        centerTitle: true,
      ),
      body: FutureBuilder(
          future: myFuture,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return ListView.builder(
                itemCount: students.length,
                itemBuilder: (context, index) {
                  return Container(
                    child: Card(
                      child: Padding(
                        padding: EdgeInsets.all(15.0),
                        child: Column(
                          children: [
                            Text(students[index].id.toString()),
                            Text(students[index].name.toString())
                          ],
                        ),
                      ),
                    ));
                });
            } else {
              return Center(child: CircularProgressIndicator());
            }
          })
    );
  }
}

请注意,我已将 HTML 实体编码转换为正常字符,以便代码能够正确工作。如果你有关于代码的其他问题,可以提出。

英文:

The Future builder in my Flutter app is fetching data twice, as opposed to fetching data just once.

class StudentListView extends StatefulWidget {
  @override
  State&lt;StudentListView&gt; createState() =&gt; _StudentListViewState();
}

class _StudentListViewState extends State&lt;StudentListView&gt; {

  List&lt;StudentModel&gt; students = [];

  late Future myFuture;

  Future&lt;List&lt;StudentModel&gt;&gt; getStudents() async {

    var response = await http.get(Uri.https(BASE_URL, APP_INTERSNSHIP_URL));

    var studentData = jsonDecode(response.body);

    for (var student in studentData) {

      final singlestudent = StudentModel(
          id: student[&quot;id&quot;],
          name: student[&quot;name&quot;]);
      students.add(singleStudent);
    }
    return students;
  }

  @override
  void initState() {
    myFuture = getstudents();
    super.initState();
  }

  Widget build(BuildContext context) {
    getstudents();
    return Scaffold(
      appBar: AppBar(
        title: Text(
          APP_TITLE,
        ),
        centerTitle: true,
      ),
      body: FutureBuilder(
          future: myFuture,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return ListView.builder(
                itemCount: students.length,
                itemBuilder: (context, index) {
                  return Container(
                    child: Card(
                      child: Padding(
                        padding: EdgeInsets.all(15.0),
                        child: Column(
                          children: [
                            Text(students[index].id.toString()),
                            Text(students[index].name.toString())
                          ],
                        ),
                      ),
                    ));
                });
            } else {
              return Center(child: CircularProgressIndicator());
            }
          })
    );
  }
}

I've followed various articles, but nothing is working. Still after doing this, the app is fetching data twice.

P.S.: Is this is a standard way to fetching data in Flutter or is there something better?

P.S.S: All required libraries are added in the code, and the code doesn't have any errors. It is just fetching data twice.

答案1

得分: 1

Widget build(BuildContext context) {
    getstudents(); &lt;------ 罪魁祸首,调用了两次
    return Scaffold(
        appBar: AppBar(
          title: Text(
            APP_TITLE,
          ),
          centerTitle: true,
        ),
        body: FutureBuilder(
            future: myFuture, &lt;------ 正确的调用位置
英文:
Widget build(BuildContext context) {
    getstudents(); &lt;------ culprit, called it twice
    return Scaffold(
        appBar: AppBar(
          title: Text(
            APP_TITLE,
          ),
          centerTitle: true,
        ),
        body: FutureBuilder(
            future: myFuture, &lt;------ right place to call

答案2

得分: 0

不翻译代码部分,只翻译文本部分:

"To answer your question, I guess you have already figured out, that you had called it twice,"

"为了回答你的问题,我猜你已经明白,你已经调用了它两次,"

"To add on to it, you could directly use getStudents in the future, instead of setting it to the variable myFuture"

"此外,你可以直接在将来使用 getStudents,而不是将它赋给变量 myFuture"

"Remove the following lines"

"删除以下行"

"late Future myFuture;"

"late Future myFuture;"

"@override\nvoid initState() {\n// myFuture = getstudents(); No more needed\nsuper.initState();\n}"

"@override\nvoid initState() {\n// myFuture = getstudents(); 不再需要\nsuper.initState();\n}"

"And you can as well define List&lt;StudentModel&gt; students = [];" inside the getStudents()` as it is just used locally."

"而且你可以在 getStudents() 内部定义 `List<StudentModel> students = [];",因为它只在本地使用。"

英文:

To answer your question, I guess you have already figured out, that you had called it twice,

To add on to it, you could directly use getStudents in the future, instead of setting it to the variable myFuture

body: FutureBuilder(
            future: getStudents(), // directly call it here 

Remove the following lines

late Future myFuture;
  @override
  void initState() {
    // myFuture = getstudents(); No more needed
    super.initState();
  }

And you can aswell define List&lt;StudentModel&gt; students = []; inside the getStudents() as it is just used locally .

huangapple
  • 本文由 发表于 2023年3月7日 00:31:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定