将Flutter List <string> JSON转换为小部件

时间:2018-09-03 09:38:58

标签: json dart flutter

我在资产文件夹中有一个JSON文件

States.json

{
  "name" : "State List",
  "states" : [
   "Johor",
    "Kedah",
    "Kelantan",
    "Kuala Lumpur",
    "Melaka",
    "Negeri Sembilan",
    "Pulau Pinang",
    "Perak",
    "Perlis",
    "Pahang",
    "Terengganu",
    "Sabah",
    "Sarawak",
    "Selangor",
    "Wilayah Persekutuan"
  ]
}

我为状态创建了一个模型类:

state_model.dart

class States{

  String name;
  List<String> states;

  States({this.name, this.states});

  factory States.fromJson(Map<String, dynamic> json){

    var statesJson = json["states"];
    List<String> stateList = new List<String>.from(statesJson);

    return States(
      name: json["name"],
      states: stateList
    );
  }
}

这是 main.dart 文件:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'dart:async' show Future;
import 'dart:convert';
import 'package:state_json/model/state_model.dart';

//get the assets
Future<String> loadAssets() async{
  return await rootBundle.loadString('assets/states.json');
}

//get the states from the assets
Future loadStates() async{
  String jsonState =  await loadAssets();
  final jsonResponse = json.decode(jsonState);

  States states = new States.fromJson(jsonResponse);
  print(states.states);
  return states.states;
}

void main() {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() {
    return new MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        home: new Scaffold(
          appBar: new AppBar(
              title: new Text("States JSON")
          ),
            body: new FutureBuilder(
                future: loadStates(),
                builder: (context, snapshot){
                  if(snapshot.hasData){
                    return new ListView.builder(
                        itemBuilder: (context, index){
                          new ListTile(
                            title: new Text("${snapshot.data}"),
                          );
                        });
                  }else{
                    return new Center(child: new CircularProgressIndicator());
                  }
                })
        )
    );
  }
}

我目前面临的问题是,我可以在终端中打印出字符串的值。

I/flutter (16482): [Johor, Kedah, Kelantan, Kuala Lumpur, Melaka, Negeri Sembilan, Pulau Pinang, Perak, Perlis, Pahang, Terengganu, Sabah, Sarawak, Selangor, Wilayah Persekutuan]

但是我对如何将值插入FutureBuilder.builder毫无头绪,后者会进入ListView.builder,然后再进入ListTile以显示状态列表。

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

这里可能有两个问题:

  1. return中没有itemBuilder语句。所以它返回 null
  2. loadStates()的返回类型为Future。我认为它     应该是Future<List<String>>

然后您可以通过索引访问数据:

return new ListView.builder(
  itemBuilder: (context, index){
    if(index >= snapshot?.data?.length ?? 0) return null;

    return new ListTile(
      title: new Text("${snapshot.data[index]}"),
    );
});

注意:我没有测试代码。

答案 1 :(得分:2)

为简化@Letsar的回答:

我们还可以将 string sep = ""; StringBuilder sb = new StringBuilder(); foreach(var l in label.Rows) { sb.Append(sep).Append(l.Text); sep = ",''"; } 参数传递给itemCount以指定列表中的元素数,而不是返回ListView.builder以将索引标记为不适用。下面的示例:

null