简体   繁体   English

Flutter 如何使用列表来创建类似的小部件 白色implicit-case 和implicity-dynamic 设置为false

[英]Flutter how to use Lists to create similar widgets white implicit-case and implicity-dynamic set to false

I'm trying to be better about typing in flutter/dart.我正在尝试更好地输入颤振/飞镖。 To force this, I made an analysis_options.yaml with:为了强制执行此操作,我做了一个 analysis_options.yaml :

 analyzer:
  strong-mode:
    implicit-casts: false
    implicit-dynamic: false

and that works great, but I have a hard time with code like the following:这很好用,但是我很难使用如下代码:

Widget build(BuildContext context) {

    return Column(
      children: [...widgetList()]);
  }

  widgetList(){
     List<Map<String,dynamic>> defineWidgets = [
      {"text":"beer", "color": Colors.blue}, // <-- Missing type arguments for map literal. Try adding an explicit type like 'dynamic' or enable implicit dynamic in your analysis options.
      {"text":"wine", "color": Colors.red},
    ];
    List<Widget> finalWidgets =[];
    for(int i = 0; i < defineWidgets.length; i++ ){
      finalWidgets.add(
        Expanded(child:Container(
          child:Text(defineWidgets[i]['text']), // <-- the argument type 'dynamic' can't be assigned to the parameter type 'String'
          color:defineWidgets[i]['color']
        ))
      );
    }
    return finalWidgets;
  }

I tried using cast() to no avail.我尝试使用 cast() 无济于事。 Is there a way to do this of function without setting implicit-casts and implicit-dynamic to true?有没有办法做到 function 而不将隐式转换和隐式动态设置为真?

The error "Missing type arguments for map literal. Try adding an explicit type like 'dynamic' or enable implicit dynamic in your analysis options."错误“缺少 map 文字的类型 arguments。尝试在分析选项中添加显式类型,如“动态”或启用隐式动态。” seems to require you to cast <String,dynamic> on each Map entry for defineWidgets .似乎要求您在 defineWidgets 的每个defineWidgets条目上投射<String,dynamic> Though the code you've provided seems to work fine on DartPad.尽管您提供的代码似乎在 DartPad 上运行良好。 The declaration could look something similar to.声明可能类似于。

List<Map<String,dynamic>> pricing = [
  <String, dynamic>{"name":"beer", "price": 5},
  <String, dynamic>{"name":"wine", "price": 10},
];
  
for(Map<String,dynamic> product in pricing){
  print('${product['name']} Price: ${product['price']}');
}

As for Text(defineWidgets[i]['text']) , the Widget can only handle String value.至于Text(defineWidgets[i]['text']) ,Widget 只能处理 String 值。 But since we're fetching a dynamic value from Map<String, dynamic> , we need to cast the value as a String for the Widget to know that value is indeed a String.但是由于我们从Map<String, dynamic>获取动态值,我们需要将该值转换为字符串,以便 Widget 知道该值确实是一个字符串。

`Text(defineWidgets[i]['text'] as String)`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM