0

I have an array that looks like this

final thisCategory = [
    {
      'category': 'Social Life',
      'data': [
        {'amount': 2000, 'content': 'thanks', 'date': DateTime.now()}
      ]
    },
    {
      'category': 'Food',
      'data': [
        {'amount': 2000, 'content': 'thanks','date': DateTime.now()},
        {'amount': 2000, 'content': 'thanks','date': DateTime.now()}
      ]
    }
  ];

and this is how my app looks

enter image description here

my widget look like this

Expanded(
                child: Container(
                  child: ListView.builder(
                    itemBuilder: (context, index) => TransactitonTile(
                      category: thisCategory[index]['category'],
                      amount: amountCategory[index]['amount'].toString(),
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => Scaffold(
                              body: SafeArea(
                                child: Column(
                                  children: [
                                    Text(thisCategory[index]['category']),
                                    Expanded(
                                      child: Container(
                                        child: ListView.builder(
                                          itemBuilder: (context, index) =>
                                              ListTile(
                                            leading: //this is where i want to show 'date' element,
                                            trailing: //this is where i want to show 'amount' element,
                                            title: //this is where i want to show 'content' element,
                                          ),
                                        ),
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ),
                        );
                      },
                    ),
                    itemCount: thisCategory.length,
                  ),
                ),
              )

so when the user presses on one of the 'category' like I showed above, then the user will go to the next page which will display what 'content' is in that 'category'. I've tried to display the 'content', but all the 'content' from all the 'category' also appear in the next page. how to fix this?

2
  • What do you mean by all the content be can you please give the example based on the data you provided. Commented Jun 30, 2020 at 14:18
  • @SagarAcharya for example when I press 'Food' in my app, it will go to a new page that contains ListView.builder. which displays all 'content' from 'data' with 'category': 'Food'. so also when I press 'Social Life' and etc. Commented Jun 30, 2020 at 14:32

1 Answer 1

2

From the above sample that you provided i have created a example for you:

Following is the smaple json file that you provided

[
    {
       "category":"Social Life",
       "data":[
          {
             "amount":2000,
             "content":"thanks",
             "date":"DateTime.now()"
          }
       ]
    },
    {
       "category":"Food",
       "data":[
          {
             "amount":2000,
             "content":"thanks",
             "date":"DateTime.now()"
          },
          {
             "amount":2000,
             "content":"thanks",
             "date":"DateTime.now()"
          }
       ]
    }
 ]

And this is the main ui and below is the model class for that.

import 'package:flutter/material.dart';
import 'dart:convert';
// To parse this JSON data, do
//
//     final category = categoryFromJson(jsonString);



void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Users'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Category> categoryList = List();
  bool _isLoading = false;
  _getUsers() async {
    setState(() {
      _isLoading = true;
    });

    var data =
        await DefaultAssetBundle.of(context).loadString("assets/test.json");

    categoryList = categoryFromJson(data);

    setState(() {
      _isLoading = false;
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: Container(
        child: ListView.builder(
          itemCount: categoryList.length,
          itemBuilder: (BuildContext context, int index) {
            return GestureDetector(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => DetailPage(
                            category: categoryList[index],
                          )),
                );
              },
              child: Card(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(categoryList[index].category),
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

class DetailPage extends StatefulWidget {
  final Category category;

  DetailPage({this.category});

  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: ListView.builder(
          itemCount: widget.category.data.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
                child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                children: <Widget>[
                  Text(widget.category.data[index].amount.toString()),
                  Text(widget.category.data[index].content),
                  Text(widget.category.data[index].date),
                ],
              ),
            ));
          },
        ),
      ),
    );
  }
}

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

String categoryToJson(List<Category> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Category {
  Category({
    this.category,
    this.data,
  });

  String category;
  List<Datum> data;

  factory Category.fromJson(Map<String, dynamic> json) => Category(
        category: json["category"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "category": category,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  Datum({
    this.amount,
    this.content,
    this.date,
  });

  int amount;
  String content;
  String date;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        amount: json["amount"],
        content: json["content"],
        date: json["date"],
      );

  Map<String, dynamic> toJson() => {
        "amount": amount,
        "content": content,
        "date": date,
      };
}

Just let me know if it work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.