ravihabibillah / money_writer_app

This project is for Capstone in Independent Studies program from Dicoding X Kampus Merdeka
3 stars 1 forks source link

Mendapatkan data id dan name category sekaligus di dropdown #10

Closed ryfazrin closed 2 years ago

ryfazrin commented 2 years ago

Belum bisa

data id category untuk value dropDownItem data name category untuk child dropDownItem

// kategori
              Consumer<CategoryProvider>(
                builder: (context, provider, child) {
                  if (provider.statePengeluaran == ResultState.HasData) {
                    // data category
                    var getCategory = typePengeluaran
                        ? provider.categoriesPengeluaran
                        : provider.categoriesPemasukan;

                    // var categoryMapToList = getCategory.map((e) => e.name).toList();

//=========================
                    var categoryMapToList =
                        getCategory.map((e) => {e.id: e.name});

                    print(categoryMapToList.single);
                    print(categoryMapToList.toList());
// =====================

                    var _firstDataWithCategoryMap =
                        //   categoryMapToList.map((String value) {
                        // return DropdownMenuItem(
                        //   value: value,
                        //   child: Text(value),
                        // );
                        ['tes', 'tes1'].map((String value) {
                      return DropdownMenuItem(
                        value: value,
                        child: Text(value),
                      );
                    });

                    return DropdownButtonFormField<String>(
                      items: _firstDataWithCategoryMap.toList(),
                      onChanged: (String? newValue) {
                        setState(() {
                          dropdownValue = newValue!;
                        });
                      },
                      decoration: InputDecoration(
                        label: Text('Kategori'),
                        icon: Icon(Icons.category),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5.0),
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter some text';
                        }
                        return null;
                      },
                    );
                  } else {
                    return Center(
                      child: Text(provider.message),
                    );
                  }
                },
              ),
ryfazrin commented 2 years ago

Karena belum bisa mendapatkan id kategori, sementara aku ubah table transaction Dari semula ini :

await db.execute('''CREATE TABLE $_tblTransaction (
             id INTEGER PRIMARY KEY AUTOINCREMENT,
             description TEXT,
             amount INTEGER NOT NULL,
             transaction_date TEXT,
             id_categories INTEGER,
             type TEXT NOT NULL,
             FOREIGN KEY (id_categories) REFERENCES $_tblCategories (id) ON DELETE NO ACTION ON UPDATE NO ACTION
           )''');

Menjadi :

await db.execute('''CREATE TABLE $_tblTransaction (
             id INTEGER PRIMARY KEY AUTOINCREMENT,
             description TEXT,
             amount INTEGER NOT NULL,
             transaction_date TEXT,
             categories TEXT,
             type TEXT NOT NULL,
             FOREIGN KEY (categories) REFERENCES $_tblCategories (name) ON DELETE NO ACTION ON UPDATE NO ACTION
           )''');
ravihabibillah commented 2 years ago
 var _firstDataWithCategoryMap =
      //   categoryMapToList.map((String value) {
      // return DropdownMenuItem(
      //   value: value,
      //   child: Text(value),
      // );
    ['tes', 'tes1'].map((String value) {
  return DropdownMenuItem(
    value: value,
    child: Text(value),
  );
});

untuk yg ini, dia nge set nilai dari map ke list kan? trus yg di komen itu ngga bisa tadi? bagian

String value

itu value itu apa? key nya apa valuenya?

ryfazrin commented 2 years ago

@ravihabibillah

value aja itu, karna data di dapat dari categoryMapToList, bentuk nya list aja

ga ada key

ryfazrin commented 2 years ago

yang di komen yang Berhasil tampil tapi cuman name aja yg d dapat.

jadi sebulumnya gini kodenya

...
var categoryMapToList = getCategory.map((e) => e.name).toList();

var _firstDataWithCategoryMap =
         categoryMapToList.map((String value) {
       return DropdownMenuItem(
         value: value,
         child: Text(value),
       );
});
...
ravihabibillah commented 2 years ago
 var categoryMapToList = getCategory.map((e) => {e.id: e.name});

trus yg e.id itu? kosong?

ryfazrin commented 2 years ago

@ravihabibillah e.id ada vi tapi aku bingung nge map lagi ke _firstDataWithCategoryMap menjadi kembalian DropdownMenuItem

ravihabibillah commented 2 years ago

coba yg gini https://stackoverflow.com/questions/57234575/dart-convert-map-to-list-of-objects

ini yg return bisa ngga ngembaliin nilai DropdownMenuItem? jadi list?

return DropdownMenuItem(
         value: value,
         child: Text(value),
       );
ryfazrin commented 2 years ago

@ravihabibillah iya vi DropdownMenuItem itu widget kan ya aku pengen yang didalam widget DropdownMenuItem

value: isinya `id`,
child: isinya Text(`name`),
ravihabibillah commented 2 years ago
var _firstDataWithCategoryMap =
         categoryMapToList.entries.map((entry) {
       return DropdownMenuItem(
         value: entry.key,
         child: Text(entry.value),
       );
});

coba gitu, bisa ngga?

ryfazrin commented 2 years ago

@ravihabibillah w coba

ryfazrin commented 2 years ago

error tipe datanya vi dibagian items: coba.toList(),

var categoryMapToList = getCategory.map((e) => {e.id: e.name});

var coba = categoryMapToList.map((entry) {
  return DropdownMenuItem(
    value: entry.keys,
    child: Text(entry.values.toString()),
  );
});

return DropdownButtonFormField<String>(
  items: coba.toList(),
  onChanged: (String? newValue) {
    setState(() {
      dropdownValue = newValue!;
    });
  },
  decoration: InputDecoration(
    label: Text('Kategori'),
    icon: Icon(Icons.category),
    border: OutlineInputBorder(
      borderRadius: BorderRadius.circular(5.0),
    ),
  ),
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'Please enter some text';
    }
    return null;
  },
);

Errornya

lib/ui/home/transaction_add_update_page.dart:118:35: Error: The argument type 'List<DropdownMenuItem<Iterable<int?>>>' can't be assigned to the parameter type 'List<DropdownMenuItem<String>>?'.
 - 'List' is from 'dart:core'.
 - 'DropdownMenuItem' is from 'package:flutter/src/material/dropdown.dart' ('/D:/Program/src/flutter/packages/flutter/lib/src/material/dropdown.dart').
 - 'Iterable' is from 'dart:core'.
                      items: coba.toList(),
                                  ^
ravihabibillah commented 2 years ago

coba ini

ryfazrin commented 2 years ago

ok w coba

ryfazrin commented 2 years ago

Bisa vi pake ini https://stackoverflow.com/questions/56194874/the-argument-type-listiterabledropdownmenuitemint-cant-be-assigned-to-t

tapi sedikit berbeda kasusnya

// get data category lalu di map
var categoryMap = getCategory.map((e) => {e.id: e.name});

// aku coba ubah ke list
print(categoryMapToList.toList()); // hasil :  [{4: dipintai reja}, {5: pengeluaran 1}, {6: pengelurandd 2}, {7: pengelsbrf }]

// setelah itu aku coba lagi map agar bisa nantinya custom ke DropdownMenuItem 
// tapi hasilnya malah ada tanda kurung () gitu
print(categoryMapToList.toList().map((entry) {
    return entry.keys;
}).toList()); // hasil : [(4), (5), (6), (7)]

// bingungkan, aku coba konversi ke string lalu aku filter kurungnya
print(categoryMapToList.toList().map((entry) {
  return entry.keys
    .toString()
    .replaceAll(RegExp(r'[^0-9\.]'), '');
 }).toList()); // hasil : [4, 5, 6, 7] sesuai dengan `ekspetasi` tapi tipe data masih string

// yaudah aku implementasikan ke sini
var coba = categoryMapToList.map((entry) {
  return DropdownMenuItem(
    value: entry.keys
        .toString()
        .replaceAll(RegExp(r'[^0-9]'), ''),
    child: Text(entry.values
        .toString()
        .replaceAll(RegExp(r'[^a-z\A-Z\ ]'), '')),
  );
});
...
return DropdownButtonFormField(
    items: coba.toList(),
    ...
),
...
// hasil dari DropdownButtonFormField ku konversi lagi jadi integer
print(int.tryParse(dropdownValue!)); // berhasil
...
// berhasil