简体   繁体   中英

How to show an Array Element for Widget on Flutter

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

在此处输入图像描述

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?

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.

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