list in json object flutter code example
Example 1: flutter json to list
List to JSON:
_______________________________________________________________________________
List<String> fruits = ['Apple', 'Banana', 'Orange', 'Strawberry'];
String jsonFruits = jsonEncode(fruits);
________________________________________________________________________________
JSON to List:
________________________________________________________________________________
You need to convert each item individually
var json = jsonEncode(jsonFruits.map((e) => e.toJson()).toList());
or pass an toEncodable function
var json = jsonEncode(jsonFruits, toEncodable: (e) => e.toJsonAttr());
Example 2: json in listview flutter
Future<Post> fetchPost() async {
final response =
await http.get('http://simone.fabriziolerose.it/index.php/Hello/dispdataflutter');
if (response.statusCode == 200) {
return Post.fromJson(json.decode(response.body));
} else {
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}");
}
return CircularProgressIndicator();
},
),
),
),
);
}
}