почему он возвращает нулевое значение после разбора json + с помощью шаблона блока - PullRequest
0 голосов
/ 29 апреля 2019

Я пытаюсь применить шаблон BLoC к своему коду, который просто генерирует категории для вида сетки, но кое-как, как это не работает, хотя я делал то же самое в этой статье, но без использования API вместо этого я использовал локальный файл Json.

вот Категория_Модели

class CategoryModel {
 List<_Category> _Categories = [];

 CategoryModel.fromJson(Map<String, dynamic> parsedJson) {
   print(parsedJson['Categories'].length);
   List<_Category> temp = [];
   for (int i = 0; i < parsedJson['Categories'].length; i++) {
     //_Category is the constructor of _Category Class line number 21
     _Category category = _Category(parsedJson['Categories'][i]);
     temp.add(category);
   }
   _Categories = temp;
 }

 List<_Category> get categories => _Categories;
}

class _Category {
 int _id;

 String _name;

 String _iconPath;

 _Category(category) {
   _id = category['id'];
   _name = category['name'];
   _iconPath = category['iconPath'];
 }

 int get id => _id;

 String get name => _name;

 String get iconPath => _iconPath;
}

и здесь, где он приходит ноль

Future<CategoryModel> fetchCategoryList() async {
   final jsonCategory = await rootBundle.loadString("assets/CategoryList.json");
   final mapJsonCategory = Map.from(jsonDecode(jsonCategory));

   return CategoryModel.fromJson(mapJsonCategory);
 }

здесь находится Category_List.dart

import 'package:flutter/material.dart';

import '../blocs/category_bloc.dart';
import '../models/category_model.dart';

class CategoryList extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return CategoryListState();
  }
}

class CategoryListState extends State<CategoryList> {
  @override
  void initState() {
    super.initState();
    bloc.fetchAllCategoryList();
  }

  @override
  void dispose() {
    bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Mazaya'),
      ),
      body: StreamBuilder(
        stream: bloc.allCategories,
        builder: (context, AsyncSnapshot<CategoryModel> snapshot) {
          if (snapshot.hasData) {
            return buildList(snapshot);
          } else if (snapshot.hasError) {
            return Text(snapshot.error.toString());
          }
          return Center(child: CircularProgressIndicator());
        },
      ),
    );
  }

  Widget buildList(AsyncSnapshot<CategoryModel> snapshot) {
    return GridView.builder(
      itemCount: snapshot.data.categories.length,
    );
  }
}

JSON FILE

{
  "Categories": [
    {
      "id": 1,
      "name": "Restruants",
      "iconPath": " "
    },
    {
      "id": 2,
      "name": "Car Rental",
      "iconPath": " "
    },
    {
      "id": 3,
      "name": "Furniture",
      "iconPath": " "
    },
    {
      "id": 4,
      "name": "cars",
      "iconPath": " "
    },
    {
      "id": 5,
      "name": "Maintenance",
      "iconPath": " "
    },
    {
      "id": 6,
      "name": "Education",
      "iconPath": " "
    },
    {
      "id": 7
      "name": "Finess",
      "iconPath": " "
    },
    {
      "id": 8,
      "name": "Electronics",
      "iconPath": " "
    },
    {
      "id": 9,
      "name": "Medical",
      "iconPath": " "
    },
    {
      "id": 10,
      "name": "Entirtainment",
      "iconPath": " "
    }
  ]
}

Я ожидал, что результат будет заблокирован, как приложение в этой статье https://medium.com/flutterpub/architecting-your-flutter-project-bd04e144a8f1

1 Ответ

0 голосов
/ 30 апреля 2019

Привет. Прежде всего исправьте свой json, добавив запятую после числа 7, например: => "id": 7,

Затем измените метод fetchMovieList () в MovieApiProvider, как показано ниже, где мы получаем файл из ресурса с помощьюсправка "DefaultAssetBundle":

Future<ItemModel> fetchMovieList(BuildContext context) async {
//    final jsonCategory = await rootBundle.loadString("assets/CategoryList.json");
    final jsonCategory = await DefaultAssetBundle
        .of(context)
        .loadString('assets/CategoryList.json');
    print(jsonCategory);
    final mapJsonCategory = Map<String, dynamic>.from(jsonDecode(jsonCategory));
    print(mapJsonCategory);
    return ItemModel.fromJson(mapJsonCategory);
  }

Затем объявите свой json-файл в pubspec.yaml, как показано ниже:

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  assets:
  - assets/CategoryList.json

Затем измените метод buildList в вашем файле dart, как показано ниже:

Widget buildList(AsyncSnapshot<ItemModel> snapshot) {
    return GridView.builder(
        itemCount: snapshot.data.categories.length,
        gridDelegate:
        new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        itemBuilder: (BuildContext context, int index) {
          return Text(snapshot.data.categories[index].name);
        });
  }

Это будет работать:)

...