Sie sind auf Seite 1von 4

Add a New JSON Asset

○ Add a new assets line to your pubspec.yaml


name: catbox
description: View cats that are up for adoption.

...

flutter:

...

assets:
- assets/cats.json
Load JSON File

import 'dart:convert';
○ We need some Mock data to import 'package:catbox/models/cat.dart';

move forward class CatApi {


static List<Cat> allCatsFromJson(String jsonData) {
List<Cat> cats = [];
json.decode(jsonData)['cats'].forEach((cat) => cats.add(_fromMap(cat)));
return cats;
○ Create api.dart in }

./lib/services/ static Cat _fromMap(Map<String, dynamic> map) {


return new Cat(
externalId: map['id'],
name: map['name'],
description: map['description'],
avatarUrl: map['image_url'],
○ Handles the creation of the location: map['location'],
likeCounter: map['like_counter'],
Cat objects given some JSON isAdopted: map['adopted'],
pictures: new List<String>.from(map['pictures']),
data. cattributes: new List<String>.from(map['cattributes']),
);
}
}
Create a List of Cats

○ In cat_list.dart create a function to load in the cats

_loadCats() async {
String fileData = await DefaultAssetBundle.of(context).loadString("assets/cats.json");
for (Cat cat in CatApi.allCatsFromJson(fileData)) {
_cats.add(cat);
}
}

○ Finally call _loadCats() in a new override called initState()

List<Cat> _cats = [];

@override
void initState() {
super.initState(); Create a list of Cats at the
_loadCats(); top of _CatListState
}
Override the Cats toString()

○ If you try to print out a Cat object currently, you’ll just get the Objects
name.
▻ Try this, add print(_cats.toString()); to _loadCats()
○ We can override the toString method for cat.dart

@override
String toString() {
return "Cat $externalId is named $name";
}

○ Now when you try to print the Cats in the List<Cat>

[Cat 1 is named Piper, Cat 2 is named Tosca, Cat 3 is named Gwendolyn]

Das könnte Ihnen auch gefallen