flutter - Flutter:如何从JSON自定义标题

标签 flutter dart

我有一个像这样的JSON文件(link API):

[
  {
    "continentName": "North America",
    "countryFlag": "https://www.countryflags.io/us/shiny/64.png",
    "countryCode": "US",
    "countryName": "United States"
  },
  {
    "continentName": "North America",
    "countryFlag": "https://www.countryflags.io/ca/shiny/64.png",
    "countryCode": "CA",
    "countryName": "Canada"
  },
  {
    "continentName": "South America",
    "countryFlag": "https://www.countryflags.io/br/shiny/64.png",
    "countryCode": "BR",
    "countryName": "Brazil"
  },
  {
    "continentName": "South America",
    "countryFlag": "https://www.countryflags.io/in/shiny/64.png",
    "countryCode": "IN",
    "countryName": "India"
  },
  {
    "continentName": "Europe",
    "countryFlag": "https://www.countryflags.io/gb/shiny/64.png",
    "countryCode": "GB",
    "countryName": "United Kingdom"
  },
  {
    "continentName": "Europe",
    "countryFlag": "https://www.countryflags.io/de/shiny/64.png",
    "countryCode": "DE",
    "countryName": "Germany"
  }
我想显示相同的“continentName”(例如北美,南美,欧洲)的标题
enter image description here
所以请帮助我,如果可以的话使用StickyHeaderSliverAppBar那么好,这是主文件:
import 'package:ask/model/page3_model.dart';
import 'package:ask/services/page3_services.dart';
import 'package:flutter/material.dart';

class Page3 extends StatefulWidget {
  @override
  _Page3State createState() => _Page3State();
}

class _Page3State extends State<Page3> {
  List<Header> _header = [];
  @override
  void initState() {
    super.initState();

    HeaderServices.getHeader().then((header) {
      setState(() {
        _header = header;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Header')),
      body: Container(),
    );
  }
}

"It looks like your post is mostly code; please add some more details". =.= ...........................................

最佳答案

既然如此,我们可以看到与continentName相关的信息不止一个,例如,对于North America分别具有countryFlagcountryCode和'countryName',这是唯一的。因此,我们将newData保持这种格式

{
    North America: [
        [countryFlag, countryCode, countryName], 
        [countryFlag, countryCode, countryName]
    ]
}
...
因此,这就是我们使用新的Map进行操作的方式,该代码将存储与上述表示形式相同的值
  Map _newMap = {};
  
  // new Map which will store the data
  // _data is the variable name which stores your JSON Array
  _data.forEach((elem){
    if(_newMap.containsKey(elem["continentName"])){
      _newMap[elem["continentName"]].add([elem["countryFlag"], elem["countryName"], elem["countryCode"]]);
    }else{
      // Array of arrays will be stored like this
      _newMap[elem["continentName"]] = [[elem["countryFlag"], elem["countryName"], elem["countryCode"]]];
    }
  });
  
  print(_newMap);

  /*
     OUTPUT
     {North America: [[https://www.countryflags.io/us/shiny/64.png, United States, US], [https://www.countryflags.io/ca/shiny/64.png, Canada, CA]], South America: [[https://www.countryflags.io/br/shiny/64.png, Brazil, BR], [https://www.countryflags.io/in/shiny/64.png, India, IN]], Europe: [[https://www.countryflags.io/gb/shiny/64.png, United Kingdom, GB], [https://www.countryflags.io/de/shiny/64.png, Germany, DE]]}
  */
看到那个!因此,这个想法是针对每个continentName,我们可以有一个数组数组,其中包含要在特定continentName下显示的不同项目
这样,这是为您提供的最终解决方案:
class _MyHomePageState extends State<MyHomePage> {
  List<Map> _data = [
    {
      "continentName": "North America",
      "countryFlag": "https://www.countryflags.io/us/shiny/64.png",
      "countryCode": "US",
      "countryName": "United States"
    },
    {
      "continentName": "North America",
      "countryFlag": "https://www.countryflags.io/ca/shiny/64.png",
      "countryCode": "CA",
      "countryName": "Canada"
    },
    {
      "continentName": "South America",
      "countryFlag": "https://www.countryflags.io/br/shiny/64.png",
      "countryCode": "BR",
      "countryName": "Brazil"
    },
    {
      "continentName": "South America",
      "countryFlag": "https://www.countryflags.io/in/shiny/64.png",
      "countryCode": "IN",
      "countryName": "India"
    },
    {
      "continentName": "Europe",
      "countryFlag": "https://www.countryflags.io/gb/shiny/64.png",
      "countryCode": "GB",
      "countryName": "United Kingdom"
    },
    {
      "continentName": "Europe",
      "countryFlag": "https://www.countryflags.io/de/shiny/64.png",
      "countryCode": "DE",
      "countryName": "Germany"
    }
  ];
  
  // This will give out our final widget with header and data
  Widget get myWidget{
    // Consists of all the Widgets
    List<Widget> _widget = [];
    
    Map _newMap = {};
  
    // new Map which will store the data
    _data.forEach((elem){
      if(_newMap.containsKey(elem["continentName"])){
        _newMap[elem["continentName"]].add([elem["countryFlag"], elem["countryName"], elem["countryCode"]]);
      }else{
        // Array of arrays will be stored like this
        _newMap[elem["continentName"]] = [[elem["countryFlag"], elem["countryName"], elem["countryCode"]]];
      }
    });
    
    _newMap.forEach((k,v){
      List<Widget> _subHeaderItems = [];
      
      _widget.add(
        Container(
          color: Colors.grey,
          width: double.infinity,
          child: Text(k, textAlign: TextAlign.center)
        )
      );
      
      // We get the item like this item => [countryName, countryCode, countryFlag]
      v.forEach((item){
        _subHeaderItems.add(
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              SizedBox(width: 10.0),
              Image.network(
                item[0],
                width: 30.0,
                height: 20.0
              ),
              SizedBox(width: 20.0),
              Text(item[2]),
              SizedBox(width: 35.0),
              Text(item[1]),
            ]
          )
        );
        
        _subHeaderItems.add(
          Divider(height: 1.0, color: Colors.grey[300])
        );
      });
      
      _widget.add(
        Column(
         crossAxisAlignment: CrossAxisAlignment.stretch,
         children: _subHeaderItems
        )
      );
    });
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: _widget
    );
  }
  

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
         height: double.infinity,
         width: double.infinity,
         child: this.myWidget
      )
    );
  }
}
结果您将获得
Result Image
希望有帮助:)

关于flutter - Flutter:如何从JSON自定义标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62777866/

相关文章:

redux - 在 Flutter Redux Epic 中间件中,如何在流变量更改后分派(dispatch)操作?

dart - 内部 Widget 中的 Flutter setState

dart - Chrome 应用程序中的 "Refused to load the image"

list - 如何按另一个列表对列表进行排序

flutter - setstate后flutter_webview_plugin监听器(onHttpError)无法正常工作

ios - XCode CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER 标志在 flutter ios 项目中干净构建后不断重置

flutter - 在Dart中是否使用wait with return有区别吗?

flutter - 如何访问窗口小部件或刚刚单击的按钮的文本?

ssl - 使用 Dart :io WebSocket with wss://protocol (SSL)

flutter - 通过 (path.quadraticBezierTo) Flutter 从顶部为容器制作半圆