0
votes

I am working on a personal Flutter Project which contains a few locally stored JSON Files

This is the code

class CCategory extends StatefulWidget {
  @override
  _CCategory createState() => _CCategory();
}
class Prod {
  String Name;
  String Image;
  Prod({ this.Name, this.Image});
  factory Prod.fromJson(Map<String, dynamic> parsedJson) {
    return Prod(
        Name: parsedJson['Name'],
        Image: parsedJson['Image']);
  }
}
Future<String> _loadProdAsset() async {
  return await rootBundle.loadString('assets/data/Dabur.json');
}
Future<Prod> loadProd() async {
  String jsonString = await _loadProdAsset();
  final jsonResponse = json.decode(jsonString);
  return new Prod.fromJson(jsonResponse);
}

class _CCategory extends State<CCategory> {

  Prod _prod;
  bool _loaded = false;
  @override
  void initState() {
    super.initState();
    loadProd().then((s) => setState(() {
      _prod = s;
      _loaded = true;
    }));
  }
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitDown,
      DeviceOrientation.portraitUp,

    ]);
    return MaterialApp(
        title: "Dabur Products",
        theme: ThemeData(
          primaryColor: Colors.black,
        ),
        home: Scaffold(
            appBar: AppBar(
              title: Text("Dabur Products",
              ),
            ),
            body: _loaded?Center(

                child: ListView(

                    children: <Widget>[
                ListTile(
                leading: Image.asset('${_prod.Image}'),
                  title: Text('${_prod.Name}'),
    )
    ]

    )
    )
                : new Center(
              child: new CircularProgressIndicator(),
            )
        ),
    );

    }

    }

The contents of JSON file are not being loaded and this is the error I am encountering in debug

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List' is not a subtype of type 'Map<String, dynamic>'

Can someone please help me resolve this ?

1

1 Answers

0
votes

I don't know how your JSON-file looks like, but looking at your error code, json.decode(jsonString) seem to be giving you a List instead of a Map. I'd guess your JSON-file actually is a list:

[ 
  ... content ...
]

Instead, your JSON-file should look something like this (using { }):

{ 
  "Name": ...,
  "Image": ...
}