简体   繁体   中英

Flutter : How to call Local JSON Data and added to Tabbar dinamically?

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

我想要这样的应用程序

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(),
      ),
    );
  }
}

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;
  }

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

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 {
  TabController myTabController;

  List<Widget> myTabs = [];
  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, _) {
          return Scaffold(
            appBar: AppBar(
              titleSpacing: 10,
              title: const Text("My Store"),
              bottom: TabBar(
                isScrollable: true,
                controller: myTabController,
                tabs: myTabs.toList(),
              ),
            ),
            body: TabBarView(
              controller: myTabController,
              children: myTabsContent.toList(),
            ),
          );
        });
  }
}

//

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;
  }
}

数据未显示

Problem solved, here's my codes

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 {
  Future<List<Product>> _getProducts() async {
    final dataString = await rootBundle.loadString('assets/product.json');
    final List<dynamic> json = jsonDecode(dataString);
    final products = <Product>[];
    for (var v in json) {
      products.add(Product.fromJson(v));
    }
    return products;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Product>>(
      future: _getProducts(),
      builder: (c, s) {
        if (s.hasData) {
          List<Tab> tabs = <Tab>[];

          for (int i = 0; i < s.data.length; i++) {
            tabs.add(Tab(
              child: Text(
                s.data[i].title,
              ),
            ));
          }
          return DefaultTabController(
            length: s.data.length,
            child: Scaffold(
              appBar: AppBar(
                title: const Text("My Store"),
                bottom: TabBar(
                  isScrollable: true,
                  tabs: tabs,
                ),
              ),
              body: FutureBuilder<List<Product>>(
                future: _getProducts(),
                builder: (c, s) {
                  if (s.hasData) {
                    List<Widget> tabs = <Widget>[];

                    for (int i = 0; i < s.data.length; i++) {
                      tabs.add(Tab(
                        child: SingleChildScrollView(
                          physics: const BouncingScrollPhysics(
                              parent: AlwaysScrollableScrollPhysics()),
                          child: Padding(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 20, vertical: 0),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                const SizedBox(height: 30),
                                Text(
                                  s.data[i].title,
                                  textAlign: TextAlign.center,
                                  style: const TextStyle(
                                      fontSize: 20,
                                      fontWeight: FontWeight.bold),
                                ),
                                const SizedBox(height: 30),
                                Image.asset(s.data[i].image),
                                const SizedBox(height: 30),
                                Text(s.data[i].title),
                                const SizedBox(height: 30),
                                Text(s.data[i].description),
                              ],
                            ),
                          ),
                        ),
                      ));
                    }
                    return TabBarView(
                      children: tabs,
                    );
                  }
                  return Container();
                },
              ),
            ),
          );
        }
        return Scaffold(
          body: Center(
              child: Text(s.hasError ? s.error.toString() : "Loading...")),
        );
      },
    );
  }
}

// Product Model

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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM