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

问题描述 投票:0回答:1

我正在尝试在我的代码上应用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;
}

在这里,它将变为空

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

dart flutter bloc
1个回答
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);
        });
  }

它会工作:)

© www.soinside.com 2019 - 2024. All rights reserved.