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

时间:2019-04-29 07:58:27

标签: dart flutter bloc

我正在尝试在代码中应用BLoC模式,该模式只是为Grid View生成类别,但是尽管我在本文中做了相同的操作,但是没有使用api,而是使用了本地Json File,但它却不起作用。

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

此处为空

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中的应用程序一样锁定

1 个答案:

答案 0 :(得分:0)

嗨,首先,您可以在数字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);
        });
  }

它将起作用:)