1

我是 Flutter 的新手,我想知道如何在不重新加载数据的情况下将项目列表动态添加到 ListView 中FutureBuilder。当我将一个项目添加到 ListView 时,它会复制该列表,然后将该项目添加到该列表中。

以下代码包含名为 Job 的 Model 类。

JobListView 是一个包含动态 ListView 的有状态小部件。

import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
class Job {
  @required
  String company;
  String description;
  String employmentType;
  int id;
  String location;
  String position;
  List<String> skillsRequired;


  Job(
      this.company,
      this.description,
      this.employmentType,
      this.id,
      this.location,
      this.position,
      this.skillsRequired);

  Job.fromJson(Map<String, dynamic> json) {
    company = json['company'];
    description = json['description'];
    employmentType = json['employmentType'];
    id = json['id'];
    location = json['location'];
    position = json['position'];
    if (json['skillsRequired'] != null) {
      skillsRequired = new List<String>();
      json['skillsRequired'].forEach((v) {
        skillsRequired.add(v);
      });
    }
  }
}

class JobListView extends StatefulWidget {
  @override
  _JobListViewState createState() => _JobListViewState();
}

class _JobListViewState extends State<JobListView> {
  List<Job> data =  List<Job>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<Job>>(
        future: _getJob(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            data  = snapshot.data;
            return _listViewFormat(data);
          } else if (snapshot.hasError) {
            return Container();
          }
          return Center(
            child: Container(
              width: 50,
              height: 50,

              child: CircularProgressIndicator(),
            ),
          );
        },
      ) ,

      floatingActionButton: (FloatingActionButton(child: Icon(Icons.add),onPressed: (){
        setState(() {
          var j =  Job("CompanyX","Eng.5 position","Full-time",0,"Cairo","Senior",null);
          data.add(j);
        });
      },)),
    );
  }
}

ListView _listViewFormat(List<Job> data) {
  return ListView.builder(
      itemCount: data.length,
      itemBuilder: (context, index) {
        return _tile(data[index].position, data[index].description, Icons.work);
      });
}

ListTile _tile(String title, String subtitle, IconData iconData) {
  return ListTile(
    title: Text(title, style: TextStyle(fontSize: 20)),
    subtitle: Text(
      subtitle,
      style: TextStyle(fontSize: 12),
    ),
    leading: Icon(iconData),
    trailing: Icon(Icons.arrow_right),
  );
}

Future<List<Job>> _getJob() async {
  String baseUrl = 'https://mock-json-service.glitch.me';
  var response = await get(baseUrl);
  if (response.statusCode == 200) {
    List jsonResponse = json.decode(response.body);
    return jsonResponse.map((job) => new Job.fromJson(job)).toList();
  }
}
4

1 回答 1

1

查看更多解释如何处理不需要的小部件构建?

如果未来发生变化,您将看到变化

在 initState 中移动 _getJob 方法,如下所示:

class _JobListViewState extends State<JobListView> {
  List<Job> data =  List<Job>();
  Future<List<Job>> getJobFuture;

  @override
  void initState() {
    super.initState();
    getJobFuture = _getJob();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<Job>>(
        future: getJobFuture,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            data  = snapshot.data;
            return _listViewFormat(data);
          } else if (snapshot.hasError) {
            return Container();
          }
          return Center(
            child: Container(
              width: 50,
              height: 50,

              child: CircularProgressIndicator(),
            ),
          );
        },
      ) ,

      floatingActionButton: (FloatingActionButton(child: Icon(Icons.add),onPressed: (){
        setState(() {
          var j =  Job("CompanyX","Eng.5 position","Full-time",0,"Cairo","Senior",null);
          data.add(j);
        });
      },)),
    );
  }
}
于 2020-10-26T19:29:07.753 回答