skip to Main Content

i have this method inside a class


Map<String, String> value = {};
bool isReady = false;


void getData() async {
    try {
        Map<String, String> data = await CustomerData().getService(selectedService);
        isReady = true;
        setState(() {
            value = data;
        });
    } catch (e) {
        print(e);
    }
}

i’d like to loop the results inside a widget so:

@override
Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text('Customer'),
        ),
        body: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
                value.forEach((key, value) { 
                    Text('$key: $value'),
                 })  
            ],
        ),
    );
}

the only solution that i found is this but i don’t like it

@override
Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text('Customer'),
        ),
        body: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
                Text(isReady ? 'Service: value["deliver"]' : '?'),
                Text(isReady ? 'Status: value["status"]' : '?'),
                Text(isReady ? 'Note: value["note"]' : '?'),
            ],
        ),
    );
}

is possible loop a Map type that comes from a method async inside a Widget?

2

Answers


  1.     FutureBuilder(
           builder: (context, snapshot) {
             if (snapshot.hasData) {
               return Column(
                 mainAxisAlignment: MainAxisAlignment.center,
                 children: snapshot.data!.entries
                             .map((e) => Text(' ${e.key} : ${e.value} '))
                             .toList(),
               );
             }
             return const Center(child: CircularProgressIndicator());
       },
       future: data(),
    )
    
    
    Future<Map<String, dynamic>> data() => Future.value({'name': 'John', 'age': 20, 'height': 5.6});
    
    Login or Signup to reply.
  2. Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: value.entries.map((e) => Text('${e.key}: ${e.value}')).toList(),
    ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search