Home > Back-end >  Flutter : How to call Local JSON Data and added to Tabbar dinamically?
Flutter : How to call Local JSON Data and added to Tabbar dinamically?

Time:12-19

I want my codes to be shorter by using JSON. Please help, how to generate Local JSON into Tabbar? Previously I've read the thread from this website, but it calls JSON API, not LOCAL JSON. and I still don't understand how to call it

I want my app like this

I want my app like this

my JSON file (assets/product.json)

[
{
    "id": 1,
    "title": "NoteBook",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.",
    "image": "assets/img/notebook.jpg",
    "price": "Rp. 13.000.000"
},
{
    "id": 2,
    "title": "Printer",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.",
    "image": "assets/img/printer.jpg",
    "price": "Rp. 700.000"
},
{
    "id": 3,
    "title": "Mouse",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.",
    "image": "assets/img/standard-mouse.jpg",
    "price": "Rp. 1.100.000"
},
{
    "id": 4,
    "title": "Keyboard",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.",
    "image": "assets/img/rgb-keyboard.jpg",
    "price": "Rp. 2.100.000"
},
{
    "id": 5,
    "title": "Mouse Gaming",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.",
    "image": "assets/img/gaming-mouse.jpg",
    "price": "Rp. 500.000"
},
{
    "id": 6,
    "title": "Proccessor",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.",
    "image": "assets/img/procie.jpg",
    "price": "Rp. 6.000.000"
},
{
    "id": 7,
    "title": "Solid State Drive",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.",
    "image": "assets/img/ssd.jpg",
    "price": "Rp. 2.100.000"
}

]

my Product Model (ProductModel.dart)

import 'dart:convert';

List<Product> ProductFromJson(String str) =>
    List<Product>.from(json.decode(str).map((x) => Product.fromJson(x)));

class Product {
  Product({
    this.id,
    this.title,
    this.image,
    this.description,
    this.price,
  });
  final int id;
  final String title;
  final String image;
  final String description;
  final String price;

  factory Product.fromJson(Map<String, dynamic> json) => Product(
        id: json["id"],
        title: json["title"],
        image: json["image"],
        description: json["description"],
        price: json["price"],
      );

  String getTitle() {
    return title;
  }

  String getImage() {
    return image;
  }

  String getDescription() {
    return description;
  }

  String getPrice() {
    return price;
  }
}

my Main Page(MainPage.dart)

import 'package:flutter/material.dart';

class MainPage extends StatefulWidget {
  const MainPage({Key key}) : super(key: key);

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage>
    with SingleTickerProviderStateMixin {
  TabController myTabController;

  List<Widget> myTabs = [];
  List<Widget> myTabsContent = [];

  @override
  void initState() {
    super.initState();
    myTabController = TabController(vsync: this, length: myTabs.length);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        titleSpacing: 10,
        title: Text("My Store"),
        bottom: TabBar(
          labelPadding: EdgeInsets.fromLTRB(20, 0, 20, 10),
          isScrollable: true,
          controller: myTabController,
          tabs: myTabs.toList(),
        ),
      ),
      body: TabBarView(
        controller: myTabController,
        children: myTabsContent.toList(),
      ),
    );
  }
}

CodePudding user response:

This is the code after I added your code. but the data is not showing :( data not shown

CodePudding user response:

You can try this method to load products from json and use FutureBuilder to load content and show it to your tabs:

    Future<List<Product>> _getProducts() async {
    // Load json from file system
    final dataString =
    await rootBundle.loadString('assets/product.json');
    // Decode to json
    final List<dynamic> json = jsonDecode(dataString);

    // Go through each post and convert json to Post object.
      final products = <Product>[];
      json.forEach((v) {
        products.add(Product.fromJson(v));
      });
      return products;
  }

Example based on your code (you need update code to process initial for myTabs and myTabsContent basesd on result):

import 'dart:convert';

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

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage>
    with SingleTickerProviderStateMixin {
  late TabController myTabController;

  List<Widget> myTabs = const [
    Tab(icon: Icon(Icons.directions_car)),
    Tab(icon: Icon(Icons.directions_transit)),
    Tab(icon: Icon(Icons.directions_bike)),
  ];
  List<Widget> myTabsContent = [];

  Future<List<Product>> _getProducts() async {
    // Load json from file system
    final dataString = await rootBundle.loadString('assets/product.json');
    // Decode to json
    final List<dynamic> json = jsonDecode(dataString);

    // Go through each post and convert json to Post object.
    final products = <Product>[];
    json.forEach((v) {
      products.add(Product.fromJson(v));
    });
    return products;
  }

  @override
  void initState() {
    super.initState();
    myTabController = TabController(vsync: this, length: myTabs.length);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _getProducts(),
        builder: (context, AsyncSnapshot<List<Product>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return Scaffold(
              appBar: AppBar(
                titleSpacing: 10,
                title: const Text("My Store"),
                bottom: TabBar(
                  isScrollable: true,
                  controller: myTabController,
                  tabs: myTabs,
                ),
              ),
              body: TabBarView(controller: myTabController, children: [
                _buildItems(snapshot.data!.first),
                Icon(Icons.directions_transit),
                Icon(Icons.directions_bike),
              ]),
            );
          } else {
            return const Icon(Icons.directions_car);
          }
        });
  }

  Widget _buildItems(Product product) {
    return Column(
      children: [
        Text(product.title),
        Text(product.price)
      ],
    );
  }
}

//

List<Product> ProductFromJson(String str) =>
    List<Product>.from(json.decode(str).map((x) => Product.fromJson(x)));

class Product {
  Product({
    required this.id,
    required this.title,
    required this.image,
    required this.description,
    required this.price,
  });

  final int id;
  final String title;
  final String image;
  final String description;
  final String price;

  factory Product.fromJson(Map<String, dynamic> json) => Product(
        id: json["id"],
        title: json["title"],
        image: json["image"],
        description: json["description"],
        price: json["price"],
      );

  String getTitle() {
    return title;
  }

  String getImage() {
    return image;
  }

  String getDescription() {
    return description;
  }

  String getPrice() {
    return price;
  }
}

Here is result

  • Related