我已经从json获取数据。现在,我必须将多个数据传递到下一个屏幕。 我在列表视图中显示摘要,并能够将其发送到下一个屏幕。但是我在将说明,位置之类的多个数据发送到下一屏幕时遇到问题。
1)这是JSON数据。
List data = {
"kind": "calendar#events",
"etag": "\"p32gchndvjbiug0g\"",
"updated": "2020-04-13T10:36:30.548Z",
"timeZone": "Asia/Kolkata",
"items": [
{
"kind": "calendar#event",
"summary": "test event",
"description": "test description",
"location": "Maharashtra, India",
"creator": {
"email": "r******ar@gmail.com"
},
"start": {
"dateTime": "2022-09-23T16:30:00+05:30"
},
},
{
"kind": "calendar#event",
"summary": "DEMO",
"description": "Join Zoom Meeting\u003cbr\u003e",
"location": "Nyati Eureka ( Commercial Complex), K",
"creator": {
"email": "k*********ar.rohit@gmail.com",
"self": true
},
"start": {
"dateTime": "2020-04-13T10:00:00+05:30"
},
}
]
}
class Event {
String kind;
String etag;
String summary;
DateTime updated;
String timeZone;
List<Item> items;
Event({
this.kind,
this.etag,
this.summary,
this.updated,
this.timeZone,
this.accessRole,
this.items,
});
factory Event.fromJson(Map<String, dynamic> json) => Event(
kind: json["kind"],
etag: json["etag"],
summary: json["summary"],
updated: DateTime.parse(json["updated"]),
timeZone: json["timeZone"],
items: List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"kind": kind,
"etag": etag,
"summary": summary,
"updated": updated.toIso8601String(),
"timeZone": timeZone,
"items": List<dynamic>.from(items.map((x) => x.toJson())),
};
}
class Item {
String kind;
String summary;
String description;
String location;
Item({
this.kind,
this.summary,
this.description,
this.location,
});
factory Item.fromJson(Map<String, dynamic> json) => Item(
kind: json["kind"],
summary: json["summary"],
description: json["description"] == null ? null : json["description"],
location: json["location"] == null ? null : json["location"],
);
Map<String, dynamic> toJson() => {
"kind": kind,
"summary": summary,
"description": description == null ? null : description,
"location": location == null ? null : location,
};
}
2)JSON响应
Future<Map<DateTime, List>> getTask() async {
Map<DateTime, List> mapFetch = {};
await Future.delayed(const Duration(seconds: 1), () {});
String link =
"LINK";
var res = await http
.get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
List data = jsonDecode(res.body)['items'];
if (res.statusCode == 200) {
Event event = eventFromJson(res.body);
return mapFetch;
}
void _onDaySelected(DateTime day, List events) {
setState(() {
_selectedEvents = events;
});
}
3)第一个屏幕上的ListView
Widget _buildEventList() {
return ListView(
children: _selectedEvents
.map(
(event) => Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 4.0),
color: Colors.white,
child: ListTile(
leading: Icon(
Icons.album,
color: Colors.blue,
),
onTap: () =>
getItemAndNavigate(event, context),
title: Text(
event.toString(),
),
),
),
)
.toList(),
);
}
getItemAndNavigate(String _selectedEvents, BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EventDetail(itemHolder: _selectedEvents)));
}
4)我需要将数据输入到下一个屏幕中,如何获取?
答案 0 :(得分:1)
您可以在下面复制粘贴运行完整代码
步骤1:在getTask(
中,您可以使用Future<Map<DateTime, List<Item>>> getTask()
步骤2:针对mapFetch[event.items[i].start.dateTime] = [event.items[i]];
步骤3:事件详细信息
class EventDetail extends StatefulWidget {
List<Item> itemHolder;
EventDetail({this.itemHolder});
@override
_EventDetailState createState() => _EventDetailState();
}
class _EventDetailState extends State<EventDetail> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Detail"),
),
body: Text(
' ${widget.itemHolder[0].creator.email} ${widget.itemHolder[0].description}'));
}
}
工作演示
完整代码
import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
Event eventFromJson(String str) => Event.fromJson(json.decode(str));
String eventToJson(Event data) => json.encode(data.toJson());
class Event {
String kind;
String etag;
DateTime updated;
String timeZone;
List<Item> items;
Event({
this.kind,
this.etag,
this.updated,
this.timeZone,
this.items,
});
factory Event.fromJson(Map<String, dynamic> json) => Event(
kind: json["kind"],
etag: json["etag"],
updated: DateTime.parse(json["updated"]),
timeZone: json["timeZone"],
items: List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"kind": kind,
"etag": etag,
"updated": updated.toIso8601String(),
"timeZone": timeZone,
"items": List<dynamic>.from(items.map((x) => x.toJson())),
};
}
class Item {
String kind;
String summary;
String description;
String location;
Creator creator;
Start start;
Item({
this.kind,
this.summary,
this.description,
this.location,
this.creator,
this.start,
});
factory Item.fromJson(Map<String, dynamic> json) => Item(
kind: json["kind"],
summary: json["summary"],
description: json["description"],
location: json["location"],
creator: Creator.fromJson(json["creator"]),
start: Start.fromJson(json["start"]),
);
Map<String, dynamic> toJson() => {
"kind": kind,
"summary": summary,
"description": description,
"location": location,
"creator": creator.toJson(),
"start": start.toJson(),
};
}
class Creator {
String email;
Creator({
this.email,
});
factory Creator.fromJson(Map<String, dynamic> json) => Creator(
email: json["email"],
);
Map<String, dynamic> toJson() => {
"email": email,
};
}
class Start {
DateTime dateTime;
Start({
this.dateTime,
});
factory Start.fromJson(Map<String, dynamic> json) => Start(
dateTime: DateTime.parse(json["dateTime"]),
);
Map<String, dynamic> toJson() => {
"dateTime": dateTime.toIso8601String(),
};
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
List<Item> _selectedEvents;
int _counter = 0;
Map<DateTime, List<Item>> _events;
CalendarController _calendarController;
AnimationController _animationController;
void _incrementCounter() {
setState(() {
_counter++;
});
}
Future<Map<DateTime, List<Item>>> getTask() async {
Map<DateTime, List<Item>> mapFetch = {};
await Future.delayed(const Duration(seconds: 3), () {});
/*String link = baseURL + fetchTodoByDate;
var res = await http.post(Uri.encodeFull(link), headers: {"Accept": "application/json"});
if (res.statusCode == 200) {
// need help in creating fetch logic here
}*/
String responseString = '''
{
"kind": "calendar#events",
"etag": "p32gchndvjbiug0g",
"updated": "2020-04-13T10:36:30.548Z",
"timeZone": "Asia/Kolkata",
"items": [
{
"kind": "calendar#event",
"summary": "test event",
"description": "test description",
"location": "Maharashtra, India",
"creator": {
"email": "r******ar@gmail.com"
},
"start": {
"dateTime": "2022-09-23T16:30:00+05:30"
}
},
{
"kind": "calendar#event",
"summary": "DEMO",
"description": "Join Zoom Meeting\u003cbr\u003e",
"location": "Nyati Eureka ( Commercial Complex), K",
"creator": {
"email": "k*********ar.rohit@gmail.com",
"self": true
},
"start": {
"dateTime": "2020-04-13T10:00:00+05:30"
}
}
]
}
''';
Event event = eventFromJson(responseString);
for (int i = 0; i < event.items.length; i++) {
mapFetch[event.items[i].start.dateTime] = [event.items[i]];
}
return mapFetch;
}
void _onDaySelected(DateTime day, List events) {
print('CALLBACK: _onDaySelected');
setState(() {
_selectedEvents = events;
});
}
@override
void initState() {
final _selectedDay = DateTime.now();
_selectedEvents = [];
_calendarController = CalendarController();
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 400),
);
_animationController.forward();
WidgetsBinding.instance.addPostFrameCallback((_) {
getTask().then((val) => setState(() {
_events = val;
}));
//print( ' ${_events.toString()} ');
});
super.initState();
}
@override
void dispose() {
_calendarController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_buildTableCalendarWithBuilders(),
const SizedBox(height: 8.0),
const SizedBox(height: 8.0),
Expanded(child: _buildEventList()),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
Widget _buildTableCalendarWithBuilders() {
return TableCalendar(
//locale: 'pl_PL',
calendarController: _calendarController,
events: _events,
//holidays: _holidays,
initialCalendarFormat: CalendarFormat.month,
formatAnimation: FormatAnimation.slide,
startingDayOfWeek: StartingDayOfWeek.sunday,
availableGestures: AvailableGestures.all,
availableCalendarFormats: const {
CalendarFormat.month: '',
CalendarFormat.week: '',
},
calendarStyle: CalendarStyle(
outsideDaysVisible: false,
weekendStyle: TextStyle().copyWith(color: Colors.blue[800]),
holidayStyle: TextStyle().copyWith(color: Colors.blue[800]),
),
daysOfWeekStyle: DaysOfWeekStyle(
weekendStyle: TextStyle().copyWith(color: Colors.blue[600]),
),
headerStyle: HeaderStyle(
centerHeaderTitle: true,
formatButtonVisible: false,
),
builders: CalendarBuilders(
selectedDayBuilder: (context, date, _) {
return FadeTransition(
opacity: Tween(begin: 0.0, end: 1.0).animate(_animationController),
child: Container(
margin: const EdgeInsets.all(4.0),
padding: const EdgeInsets.only(top: 5.0, left: 6.0),
color: Colors.deepOrange[300],
width: 100,
height: 100,
child: Text(
'${date.day}',
style: TextStyle().copyWith(fontSize: 16.0),
),
),
);
},
todayDayBuilder: (context, date, _) {
return Container(
margin: const EdgeInsets.all(4.0),
padding: const EdgeInsets.only(top: 5.0, left: 6.0),
color: Colors.amber[400],
width: 100,
height: 100,
child: Text(
'${date.day}',
style: TextStyle().copyWith(fontSize: 16.0),
),
);
},
markersBuilder: (context, date, events, holidays) {
final children = <Widget>[];
if (events.isNotEmpty) {
children.add(
Positioned(
right: 1,
bottom: 1,
child: _buildEventsMarker(date, events),
),
);
}
if (holidays.isNotEmpty) {
children.add(
Positioned(
right: -2,
top: -2,
child: _buildHolidaysMarker(),
),
);
}
return children;
},
),
onDaySelected: (date, events) {
_onDaySelected(date, events);
_animationController.forward(from: 0.0);
},
onVisibleDaysChanged: _onVisibleDaysChanged,
);
}
void _onVisibleDaysChanged(
DateTime first, DateTime last, CalendarFormat format) {
print('CALLBACK: _onVisibleDaysChanged');
}
Widget _buildEventsMarker(DateTime date, List events) {
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: _calendarController.isSelected(date)
? Colors.brown[500]
: _calendarController.isToday(date)
? Colors.brown[300]
: Colors.blue[400],
),
width: 16.0,
height: 16.0,
child: Center(
child: Text(
'${events.length}',
style: TextStyle().copyWith(
color: Colors.white,
fontSize: 12.0,
),
),
),
);
}
Widget _buildHolidaysMarker() {
return Icon(
Icons.add_box,
size: 20.0,
color: Colors.blueGrey[800],
);
}
Widget _buildEventList() {
return ListView(
children: _selectedEvents
.map((event) => Container(
decoration: BoxDecoration(
border: Border.all(width: 0.8),
borderRadius: BorderRadius.circular(12.0),
),
margin:
const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
child: ListTile(
title: Text(event.description),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
EventDetail(itemHolder: _selectedEvents)));
},
),
))
.toList(),
);
}
}
class EventDetail extends StatefulWidget {
List<Item> itemHolder;
EventDetail({this.itemHolder});
@override
_EventDetailState createState() => _EventDetailState();
}
class _EventDetailState extends State<EventDetail> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Detail"),
),
body: Text(
' ${widget.itemHolder[0].creator.email} ${widget.itemHolder[0].description}'));
}
}
答案 1 :(得分:0)
请像下面这样编写您的下一个屏幕代码...
import 'package:flutter/material.dart';
class NextWidget extends StatefulWidget {
final String event;
NextWidget({Key key, @required this.event}) : super(key: key);
@override
_NextWidgetState createState() => _NextWidgetState(event: event);
}
class _NextWidgetState extends State<NextWidget> {
final String event;
_NextWidgetState({Key key, @required this.event});
@override
Widget build(BuildContext context) {
return Container();
}
}