Flutter load json from assets folder
1. Create a sample Flutter app
flutter create flutter_load_json_from_assets
2. Create a folder assets in the Flutter project root folder, and then create a sub-folder called data inside the assets folder, then add a json file in the data folder. Here is a sample json file: pokemon_names.json
{ "1": { "id": 1, "name": "Bulbasaur" }, "10": { "id": 10, "name": "Caterpie" }, "100": { "id": 100, "name": "Voltorb" }, "101": { "id": 101, "name": "Electrode" }, "102": { "id": 102, "name": "Exeggcute" }, "103": { "id": 103, "name": "Exeggutor" }, "104": { "id": 104, "name": "Cubone" }, "105": { "id": 105, "name": "Marowak" }, "106": { "id": 106, "name": "Hitmonlee" }, "107": { "id": 107, "name": "Hitmonchan" }, "108": { "id": 108, "name": "Lickitung" }, "109": { "id": 109, "name": "Koffing" }, "11": { "id": 11, "name": "Metapod" } }
3. In the pubspec.yaml file, specify the assets folder path.
flutter: assets: - assets/data/
4. Replace the contain in main.dart with the following.
import 'package:flutter/material.dart'; import 'dart:async' show Future; import 'dart:convert'; import 'package:flutter/services.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, title: 'Pokemons', home: HomePage(), ); } } class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override PokemonsState createState() => PokemonsState(); } class PokemonsState extends State{ List _pokemons = []; // Read content from the json file Future readJson() async { final String response = await rootBundle.loadString('assets/data/pokemon_names.json'); final Map data = await json.decode(response); List pokemons = []; data.forEach((final String key, final value) { //print("Key: {{$key}} -> value: ${value}"); pokemons.add(value); }); //print(pokemons); setState(() { _pokemons = pokemons; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: const Text( 'Load json data', ), ), body: Padding( padding: const EdgeInsets.all(25), child: Column( children: [ ElevatedButton( child: const Text('Load pokemons'), onPressed: readJson, ), // Display the data loaded from pokemon_names.json _pokemons.isNotEmpty ? Expanded( child: ListView.builder( itemCount: _pokemons.length, itemBuilder: (context, index) { return Card( margin: const EdgeInsets.all(10), child: ListTile( leading: Text(_pokemons[index]["id"].toString()), title: Text(_pokemons[index]["name"]), ), ); }, ), ) : Container() ], ), ), ); } }
5. Run the app
flutter run
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts