dart 在调用异步方法后循环Map类型

mefy6pfw  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(137)

我在一个类里有这个方法

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

我想在一个小部件中循环结果,这样:

@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'),
                 })  
            ],
        ),
    );
}

我找到的唯一解决方案是这个,但我不喜欢它

@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"]' : '?'),
            ],
        ),
    );
}

是否可以循环一个来自Widget内部异步方法的Map类型?

umuewwlo

umuewwlo1#

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});
9bfwbjaz

9bfwbjaz2#

Column(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  crossAxisAlignment: CrossAxisAlignment.stretch,
  children: value.entries.map((e) => Text('${e.key}: ${e.value}')).toList(),
),

相关问题