为什么它在解析 json + 使用 bloc 模式后返回空值

why it's returning null value after parsing json + using bloc pattern

我正在尝试在我的代码上应用 BLoC 模式,它只是为网格视图生成类别,但有些方法不起作用,尽管我在本文中做了同样的事情,但没有使用 api 而我使用了本地 Json 文件。

这里是 Category_Model

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;
}

这里是 null

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 文件

{
  "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

您好首先通过在数字 7 之后添加逗号来更正您的 json => "id": 7,

然后更改 MovieApiProvider 中的 fetchMovieList() 方法,如下所示,我们在 "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);
  }

然后在 pubspec.yaml 中声明您的 json 文件,如下所示:

# 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

然后在您的 dart 文件中更改 buildList 方法,如下所示:

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);
        });
  }

它会起作用:)