【发布时间】:2022-01-16 11:49:51
【问题描述】:
我在本地检索 json 数据并且在颤振中对单屏负向 在您的项目根目录中创建一个资产文件夹并将我的 JSON 文件放入其中。 将 JSON 文件输入到 pubspec.yaml 文件中 制作了一种将 JSON 文件读入你的 Flutter 应用程序的方法
列表屏幕
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' as rootBundle;
import 'package:license_app/data/data.dart';
import 'package:license_app/model/pqtnj_model.dart';
import 'package:license_app/page/detail.dart';
class MyList extends StatelessWidget {
MyList({Key? key}) : super(key: key);
//final list = Pquestion.generate();
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: ReadJsonData(),
builder: (context, data) {
if (data.hasData) {
var items = data.data as List<PjQuestion>;
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
contentPadding: const EdgeInsets.all(15.0),
leading: CircleAvatar(
backgroundColor: Colors.blue.shade400,
child: Text(
items[index].id.toString(),
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
title: Text(
items[index].question.toString(),
style: const TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) {
return DetailScreen(snapshot.lists[index]);
}));
},
),
elevation: 5,
margin: const EdgeInsets.all(10),
shadowColor: Colors.black12,
shape: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
borderSide: const BorderSide(color: Colors.white)),
);
});
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
));
}
Future<List<PjQuestion>> ReadJsonData() async {
final jsondata =
await rootBundle.rootBundle.loadString('assets/json/pquestion.json');
final list = json.decode(jsondata) as List<dynamic>;
return list.map((e) => PjQuestion.fromJson(e)).toList();
}
}
在选项卡上没有导航 我现在遇到的错误 “未定义的名称‘快照’。 尝试将名称更正为已定义的名称,或定义名称。”
详细画面
import 'package:flutter/material.dart';
import 'package:license_app/data/data.dart';
class DetailScreen extends StatelessWidget {
final Pquestion pquestion;
const DetailScreen(this.pquestion, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(pquestion.question),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20.0),
child: Row(
children: <Widget>[
Expanded(
child: Text(
pquestion.answer,
style: const TextStyle(fontSize: 20.0, color: Colors.black),
overflow: TextOverflow.visible,
),
)
],
)),
);
}
}
【问题讨论】:
标签: json flutter dart navigation local