Home > database >  Reading specific items from json in flutter
Reading specific items from json in flutter

Time:11-27

Hi I have json containing almost 30 items I just waan display only 10 itmes in listview and on every time I refresh page should change (in other words random items) should be selected from the json.

Is ther any way and would be great If someone can show with example.

Thanks

CodePudding user response:

Put json file in a folder called assets:

Image

Add this to pubspec.yaml:

assets:
    - assets/

Image

main.dart file:

import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  List items = [];
  int itemCount = 2;


  Future<void> readJson() async {
    final String response = await rootBundle.loadString('assets/items.json');
    final data = await json.decode(response);
    setState(() {
      items = data["items"];
    });
  }

  @override
  void initState() {
    super.initState();

    readJson();
  }

  String randomItem() {
    int random = Random().nextInt(items.length);
    print(random);
    String item = items[random]["item"];
    items.removeAt(random);
    return item;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Title"),
      ),
      body:

      items.isNotEmpty ? Center(
        child: ListView.builder(
          shrinkWrap: true,
          scrollDirection: Axis.vertical,
          itemCount: itemCount,
          itemBuilder: (context, index) => Column(
            children: [
              Text(randomItem()),
            ],
          ),
        ),
      ): const Text("Loading..."),

    );
  }
}

Json file:

{
  "items": [
    {
      "item": "One"
    },
    {
      "item": "Two"
    },
    {
      "item": "Three"
    }
  ]
}

This picks two random items which are strings from the json file.

The itemCount variable can't be longer than the number of items in the json file. Change it to 10 if you want 10 different items.

  • Related