简体   繁体   中英

how to load Json to flutter listview

I'm new to flutter and I'm developing a flutter app where I have to show in a listView the data on the database.

I get the data in JSON format.

{
    "data": [
        {
            "id": “1”,
            "testo": "Fare la spesa",
            "stato": "1"
        },
        {
            "id": “2”,
            "testo": "Portare fuori il cane",
            "stato": "1"
        },
        {
            "id": “3”,
            "testo": “jhon”,
            "stato": "0"
        }
    ]
}

The problem is that I don't load the data, I can't understand how to do it.

I should read 'Data' with an array but I don't know how to do it.

Can anyone help me figure out how to do it?

Thanks for your help.

PS. I tried this tutorial

Main.dart

Future<Post> fetchPost() async {
  final response =
  await http.get('http://simone.fabriziolerose.it/index.php/Hello/dispdataflutter');

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON.
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

class Post {
  final int id;
  final String title;
  final String body;

  Post({ this.id, this.title, this.body});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(

      id: json['id'],
      title: json['testo'],
      body: json['stato'],
    );
  }
}

void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
  final Future<Post> post;

  MyApp({Key key, this.post}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Post>(
            future: post,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner.
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

I'd rather return List of Post from fetchPost(), like below :

Future<List<Post>> fetchPost() async {
  final response = await http.get('http://simone.fabriziolerose.it/index.php/Hello/dispdataflutter');

  if (response.statusCode == 200) {
  List responseList = json.decode(response.body);
  return responseList.map((data)=>Post.fromJson(data)).toList();
  } else {
  // If that call was not successful, throw an error.
  throw Exception('Failed to load post');
  }
}

and use ListView.builder instead like this

List<Post> post;

child: ListView.builder(
  itemCount: post.length,
  physics: BouncingScrollPhysics(),
  padding: EdgeInsets.all(0),
  itemBuilder: (context, index){
    return ListAdapter(
       id: post[index].id,
       title: post[index].title,
       body: post[index].body
       );
    },
  )

This code can help you understand how to implement this functionality.

import 'dart:convert';

import 'json_objects.dart';

main(List<String> args) {
  var json = jsonDecode(_source) as Map<String, dynamic>;
  var post = Post.fromJson(json);
  for (final element in post.data) {
    print(element.id);
    print(element.title);
  }
}

final _source = '''
{
  "data": [
    {
      "id": "1",
      "testo": "Fare la spesa",
      "stato": "1"
    },
    {
      "id": "2",
      "testo": "Portare fuori il cane",
      "stato": "1"
    },
    {
      "id": "3",
      "testo": "jhon",
      "stato": "0"
    }
  ]
}''';

Result:

1
Fare la spesa
2
Portare fuori il cane
3
jhon

Used JSON data models (generated by the tool)

class Data {
  final String body;
  final String id;
  final String title;

  Data({this.body, this.id, this.title});

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
      body: json['stato'] as String,
      id: json['id'] as String,
      title: json['testo'] as String,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'stato': body,
      'id': id,
      'testo': title,
    };
  }
}

class Post {
  final List<Data> data;

  Post({this.data});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      data: _toObjectList(json['data'], (e) => Data.fromJson(e)),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'data': _fromList(data, (e) => e.toJson()),
    };
  }
}

List _fromList(data, Function(dynamic) toJson) {
  if (data == null) {
    return null;
  }
  var result = [];
  for (var element in data) {
    var value;
    if (element != null) {
      value = toJson(element);
    }
    result.add(value);
  }
  return result;
}

List<T> _toObjectList<T>(data, T Function(Map<String, dynamic>) fromJson) {
  if (data == null) {
    return null;
  }
  var result = <T>[];
  for (var element in data) {
    T value;
    if (element != null) {
      value = fromJson(element as Map<String, dynamic>);
    }
    result.add(value);
  }
  return result;
}

/*
Post:
  data: List<Data>

Data:
  id: String
  title.testo: String
  body.stato: String
*/

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